diff --git a/CODEOWNERS b/CODEOWNERS index cd5e192f6dfec673acfd1a1c594cb33b3a173978..1e6d1e90ebe18fdf635aea24811acebd8a473d78 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -164,6 +164,23 @@ 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/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 +203,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 @@ -277,15 +293,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 +309,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 +365,83 @@ 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 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/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-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index 022394ac0493a3f2b66eed1c0b5af9b02bdab334..67b846c17b94a6acee894da72ae28cedefd2532c 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -22,6 +22,7 @@ Adds a contact. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -54,11 +55,13 @@ Adds a contact. This API uses a promise to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------ | | contact | [Contact](#contact) | Yes | Contact information.| **Return Value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<number> | Promise used to return the contact ID.| @@ -89,6 +92,7 @@ Deletes a contact based on the specified contact key. This API uses an asynchron **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------ | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -118,11 +122,13 @@ Deletes a contact based on the specified contact key. This API uses a promise to **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| **Return Value** + | Type | Description | | ------------------- | --------------------------------------------- | | Promise<void> | Promise used to return the result.| @@ -150,6 +156,7 @@ Updates a contact based on the specified contact information. This API uses an a **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -182,6 +189,7 @@ Updates a contact based on the specified contact information and attributes. Thi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -217,12 +225,14 @@ Updates a contact based on the specified contact information and attributes. Thi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ------- | --------------------------------------- | ---- | ------------------ | | contact | [Contact](#contact) | Yes | Contact information. | | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes.| **Return Value** + | Type | Description | | ------------------- | ------------------------------------------------- | | Promise<void> | Promise used to return the result.| @@ -255,6 +265,7 @@ Checks whether the ID of this contact is in the local address book. This API use **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | id | number | Yes | Contact ID. Each contact corresponds to one ID. | @@ -284,11 +295,13 @@ Checks whether the ID of this contact is in the local address book. This API use **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------ | | id | number | Yes | Contact ID. Each contact corresponds to one ID.| **Return Value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the contact ID is in the local address book, and the value **false** indicates the opposite.| @@ -316,6 +329,7 @@ Checks whether a contact is included in my card. This API uses an asynchronous c **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | id | number | Yes | Contact ID. | @@ -345,11 +359,13 @@ Checks whether a contact is included in my card. This API uses a promise to retu **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | id | number | Yes | Contact ID.| **Return Value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the contact is included in my card, and the value **false** indicates the opposite.| @@ -377,6 +393,7 @@ Queries my card. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | callback | AsyncCallback<[Contact](#contact)> | Yes | Callback used to return the result.| @@ -405,6 +422,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | attrs | [ContactAttributes](#contactattributes) | Yes | List of contact attributes. | @@ -436,11 +454,13 @@ Queries my card based on the specified contact attributes. This API uses a promi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ------------------ | | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes.| **Return Value** + | Type | Description | | ---------------------------------- | ------------------------------------------- | | Promise<[Contact](#contact)> | Promise used to return the result.| @@ -470,6 +490,7 @@ Selects a contact. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<Array<[Contact](#contact)>> | Yes | Callback used to return the result.| @@ -498,6 +519,7 @@ Selects a contact. This API uses a promise to return the result. **System capability**: SystemCapability.Applications.ContactsData **Return Value** + | Type | Description | | ----------------------------------------------- | ------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -525,6 +547,7 @@ Queries a contact based on the specified key. This API uses an asynchronous call **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -554,6 +577,7 @@ Queries contacts based on the specified key and application. This API uses an as **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -588,6 +612,7 @@ Queries contacts based on the specified key and attributes. This API uses an asy **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -620,6 +645,7 @@ Queries contacts based on the specified key, application, and attributes. This A **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -658,6 +684,7 @@ Queries contacts based on the specified key, application, and attributes. This A **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -665,6 +692,7 @@ Queries contacts based on the specified key, application, and attributes. This A | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ---------------------------------- | ----------------------------------------------- | | Promise<[Contact](#contact)> | Promise used to return the result.| @@ -699,6 +727,7 @@ Queries all contacts. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | callback | AsyncCallback<Array<[Contact](#contact)>> | Yes | Callback used to return the result.| @@ -727,6 +756,7 @@ Queries all contacts based on the specified application. This API uses an asynch **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | holder | [Holder](#holder) | Yes | Application that creates the contacts. | @@ -760,6 +790,7 @@ Queries all contacts based on the specified attributes. This API uses an asynchr **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | attrs | [ContactAttributes](#contactattributes) | Yes | List of contact attributes. | @@ -791,6 +822,7 @@ Queries all contacts based on the specified application and attributes. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | holder | [Holder](#holder) | Yes | Application that creates the contacts. | @@ -827,12 +859,14 @@ Queries all contacts based on the specified application and attributes. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ---------------------- | | holder | [Holder](#holder) | No | Application that creates the contacts.| | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -866,6 +900,7 @@ Queries contacts based on the specified phone number. This API uses an asynchron **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -895,6 +930,7 @@ Queries contacts based on the specified phone number and application. This API u **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -929,6 +965,7 @@ Queries contacts based on the specified phone number and attributes. This API us **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -961,6 +998,7 @@ Queries contacts based on the specified phone number, application, and attribute **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -998,6 +1036,7 @@ Queries contacts based on the specified phone number, application, and attribute **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | --------------------------------------- | ---- | ---------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -1005,6 +1044,7 @@ Queries contacts based on the specified phone number, application, and attribute | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -1038,6 +1078,7 @@ Queries contacts based on the specified email address. This API uses an asynchro **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | email | string | Yes | Email address of the contact. | @@ -1067,6 +1108,7 @@ Queries contacts based on the specified email address and application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | email | string | Yes | Email address of the contact. | @@ -1101,6 +1143,7 @@ Queries contacts based on the specified email address and attributes. This API u **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | email | string | Yes | Email address of the contact. | @@ -1133,6 +1176,7 @@ Queries contacts based on the specified email address, application, and attribut **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | email | string | Yes | Email address of the contact. | @@ -1170,6 +1214,7 @@ Queries contacts based on the specified email address, application, and attribut **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ---------------------- | | email | string | Yes | Email address of the contact. | @@ -1177,6 +1222,7 @@ Queries contacts based on the specified email address, application, and attribut | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -1210,6 +1256,7 @@ Queries all groups of this contact. This API uses an asynchronous callback to re **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<Array<[Group](#group)>> | Yes | Callback used to return the result.| @@ -1238,6 +1285,7 @@ Queries all groups of this contact based on the specified application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | holder | Holder | Yes | Application that creates the contacts. | @@ -1271,11 +1319,13 @@ Queries all groups of this contact based on the specified application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ---------------------- | | holder | [Holder](#holder) | No | Application that creates the contacts.| **Return Value** + | Type | Description | | ------------------------------------------- | ------------------------------------------------- | | Promise<Array<[Group](#group)>> | Promise used to return the result.| @@ -1307,6 +1357,7 @@ Queries all applications that have created contacts. This API uses an asynchrono **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<Array<[Holder](#holder)>> | Yes | Callback used to return the result.| @@ -1335,6 +1386,7 @@ Queries all applications that have created contacts. This API uses a promise to **System capability**: SystemCapability.Applications.ContactsData **Return Value** + | Type | Description | | --------------------------------------------- | ------------------------------------------------------------ | | Promise<Array<[Holder](#holder)>> | Promise used to return the result.| @@ -1362,6 +1414,7 @@ Queries the key of a contact based on the specified contact ID. This API uses an **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------- | | id | number | Yes | Contact ID. | @@ -1391,6 +1444,7 @@ Queries the key of a contact based on the specified contact ID and application. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------- | | id | number | Yes | Contact ID. | @@ -1425,12 +1479,14 @@ Queries the key of a contact based on the specified contact ID and application. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ---------------------- | | id | number | Yes | Contact ID. | | holder | [Holder](#holder) | No | Application that creates the contacts.| **Return Value** + | Type | Description | | --------------------- | ---------------------------------------------------- | | Promise<string> | Promise used to return the result.| 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-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 5620062988d8b16d374f7cfc010e2b77b378cb3a..469fcae6f1c0f82f0894422b3e2a4416fabc7a60 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -30,9 +30,10 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **Example** - ```js - let nativeHeapSize = hidebug.getNativeHeapSize(); - ``` + +```js +let nativeHeapSize = hidebug.getNativeHeapSize(); +``` ## hidebug.getNativeHeapAllocatedSize @@ -45,17 +46,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | --------------------------------- | | bigint | Size of the allocated native heap memory, in kB.| **Example** - ```js - let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); - ``` + +```js +let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); +``` ## hidebug.getNativeHeapFreeSize @@ -68,17 +70,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | ------------------------------- | | bigint | Size of the free native heap memory, in kB.| **Example** - ```js - let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); - ``` + +```js +let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); +``` ## hidebug.getPss @@ -89,17 +92,18 @@ Obtains the PSS of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | ------------------------- | | bigint | PSS of the process, in kB.| **Example** - ```js - let pss = hidebug.getPss(); - ``` + +```js +let pss = hidebug.getPss(); +``` ## hidebug.getSharedDirty @@ -110,17 +114,18 @@ Obtains the size of the shared dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | | bigint | Size of the shared dirty memory of the process, in kB.| **Example** - ```js - let sharedDirty = hidebug.getSharedDirty(); - ``` + +```js +let sharedDirty = hidebug.getSharedDirty(); +``` ## hidebug.getPrivateDirty9+ @@ -130,8 +135,8 @@ Obtains the size of the private dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | | bigint | Size of the private dirty memory of the process, in kB.| @@ -152,17 +157,18 @@ For example, if the CPU usage is **50%**, **0.5** is returned. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | | number | CPU usage of the process.| **Example** - ```js - let cpuUsage = hidebug.getCpuUsage(); - ``` + +```js +let cpuUsage = hidebug.getCpuUsage(); +``` ## hidebug.startProfiling @@ -189,7 +195,6 @@ hidebug.stopProfiling(); ``` - ## hidebug.stopProfiling stopProfiling() : void @@ -245,6 +250,7 @@ This is a system API and cannot be called by third-party applications. | serviceid | number | Yes | ID of the system service. | **Return value** + | Type | Description | | ------ | -------------------------- | | string | Absolute path of the file that contains the service information to dump. | diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index e3c08ce24cf92eda9534812d664aa466c4b7c1ef..65952c0b23946b02582d74e5be9fbc5f8c33b42d 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -60,20 +60,24 @@ Writes event information to the event file. This API uses an asynchronous callba ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` @@ -102,26 +106,30 @@ Writes event information to the event file. This API uses a promise to return th ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}).then( - (val) => { - // do something here. - } -).catch( - (err) => { - // do something here. - } -) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }).then( + (val) => { + // do something here. + } + ).catch( + (err) => { + // do something here. + } + ) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` ## RuleType @@ -177,32 +185,30 @@ Adds a watcher for event subscription. | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| -**Return value** - -| Type | Description| -| ------- | -------------------------------------------------- | -| number | Event subscription result.
- **0**: Event subscription is successful.
- A value smaller than **0**: Event subscription has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + hiSysEvent.addWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) ``` ## hiSysEvent.removeWatcher @@ -221,33 +227,31 @@ Removes a watcher used for event subscription. | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| -**Return value** - -| Type | Description| -| ------- | ----------------------------------------------------------- | -| number | Result of removing the watcher.
- **0**: Removing the watcher is successful.
- A value smaller than **0**: Removing the watcher has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + hiSysEvent.addWatcher(watcher) + hiSysEvent.removeWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) -hiSysEvent.removeWatcher(watcher) ``` ## QueryArg @@ -281,7 +285,7 @@ Defines an event query instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void| +| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| ## hiSysEvent.query @@ -302,44 +306,42 @@ Queries system events. | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | querier | [Querier](#querier) | Yes | Event query instance.| -**Return value** - -| Type | Description | -| ------- | ----------------------------------------------------------- | -| number | Event query result.
- **0**: Event query is successful.
- A value smaller than **0**: Event query has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) -hiSysEvent.query({ - beginTime: -1, - endTime: -1, - maxEvents: 5, -}, [{ - domain: "RELIABILITY", - names: ["STACK"], -}], { - onQuery: function (infos, seqs) { - // do something here. - }, - onComplete: function(reason, total) { - // do something here. - } -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) + hiSysEvent.query({ + beginTime: -1, + endTime: -1, + maxEvents: 5, + }, [{ + domain: "RELIABILITY", + names: ["STACK"], + }], { + onQuery: function (infos) { + // do something here. + }, + onComplete: function(reason, total) { + // do something here. + } + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-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-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index ec63d11121dcd5138d11d7a2e1898833deaaf9c7..1d272e9f03c4956e141456324b1eb1f05293cea8 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -47,7 +47,7 @@ Obtains the default active data network. This API uses a promise to return the r **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** | Type | Description | | --------------------------------- | ------------------------------------- | @@ -92,7 +92,7 @@ Checks whether the default data network is activated. This API uses a promise to **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** | Type | Description | | ----------------- | ----------------------------------------------- | @@ -117,6 +117,7 @@ Obtains the list of all active data networks. This API uses an asynchronous call **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.| @@ -141,7 +142,8 @@ Obtains the list of all active data networks. This API uses a promise to return **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<Array<[NetHandle](#nethandle)>> | Promise used to return the result.| @@ -198,7 +200,7 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi | --------- | ----------------------- | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------------------- | --------------------------------- | @@ -258,7 +260,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th | --------- | ----------------------- | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -**Return Value** +**Return value** | Type | Description | | --------------------------------------------- | --------------------------------- | @@ -285,6 +287,7 @@ Reports connection of the data network. This API uses an asynchronous callback t **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| @@ -312,11 +315,13 @@ Reports connection of the data network. This API uses a promise to return the re **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| @@ -343,6 +348,7 @@ Reports disconnection of the data network. This API uses an asynchronous callbac **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| @@ -370,11 +376,13 @@ Reports disconnection of the data network. This API uses a promise to return the **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| @@ -432,7 +440,7 @@ Resolves the host name by using the default network to obtain all IP addresses. | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------- | ----------------------------- | @@ -561,7 +569,7 @@ Obtains the handle of the network specified by **netSpecifier**. | netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | | timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.| -**Return Value** +**Return value** | Type | Description | | ------------------------------- | -------------------- | @@ -829,7 +837,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------- | ----------------------------- | @@ -891,7 +899,7 @@ Resolves the host name by using the corresponding network to obtain the first IP | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ----------------------------------- | ------------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-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/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index 76fc15b2e5939b5bf2c03d9ccc4bcb7a8a11f659..5aa1a084c0bc9d4a28e5504cd29f11954a46fa21 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -433,7 +433,7 @@ export default { console.log('ServiceAbility want:' + JSON.stringify(want)); console.log('ServiceAbility want name:' + want.bundleName) } catch(err) { - console.log("ServiceAbility error:" + err) + console.log('ServiceAbility error:' + err) } console.info('ServiceAbility onConnect end'); return new IdlTestImp('connect'); @@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility'; function callbackTestIntTransaction(result: number, ret: number): void { if (result == 0 && ret == 124) { - console.log("case 1 success "); + console.log('case 1 success'); } } function callbackTestStringTransaction(result: number): void { if (result == 0) { - console.log("case 2 success "); + console.log('case 2 success'); } } @@ -472,17 +472,17 @@ var onAbilityConnectDone = { testProxy.testStringTransaction('hello', callbackTestStringTransaction); }, onDisconnect:function (elementName) { - console.log("onDisconnectService onDisconnect"); + console.log('onDisconnectService onDisconnect'); }, onFailed:function (code) { - console.log("onDisconnectService onFailed"); + console.log('onDisconnectService onFailed'); } }; function connectAbility: void { let want = { - "bundleName":"com.example.myapplicationidl", - "abilityName": "com.example.myapplicationidl.ServiceAbility" + bundleName: 'com.example.myapplicationidl', + abilityName: 'com.example.myapplicationidl.ServiceAbility' }; let connectionId = -1; connectionId = featureAbility.connectAbility(want, onAbilityConnectDone); @@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _reply = new rpc.MessageParcel(); _data.writeInt(data); this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode === 0) { + if (result.errCode == 0) { let _errCode = result.reply.readInt(); if (_errCode != 0) { let _returnValue = undefined; @@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _returnValue = result.reply.readInt(); callback(_errCode, _returnValue); } else { - console.log("sendRequest failed, errCode: " + result.errCode); + console.log('sendRequest failed, errCode: ' + result.errCode); } }) } @@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _reply = new rpc.MessageParcel(); _data.writeString(data); this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode === 0) { + if (result.errCode == 0) { let _errCode = result.reply.readInt(); callback(_errCode); } else { - console.log("sendRequest failed, errCode: " + result.errCode); + console.log('sendRequest failed, errCode: ' + result.errCode); } }) } @@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager'; function testIntTransactionCallback(errCode: number, returnValue: number) { - console.log("errCode: " + errCode + " returnValue: " + returnValue); + console.log('errCode: ' + errCode + ' returnValue: ' + returnValue); } function testStringTransactionCallback(errCode: number) { - console.log("errCode: " + errCode); + console.log('errCode: ' + errCode); } function jsProxyTriggerCppStub() @@ -660,6 +660,6 @@ function jsProxyTriggerCppStub() tsProxy.testIntTransaction(10, testIntTransactionCallback); // invoke testStringTransaction - tsProxy.testStringTransaction("test", testIntTransactionCallback); + tsProxy.testStringTransaction('test', testIntTransactionCallback); } ``` diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index 70a832e1fcb12e85d4fc742b171fd9bb33a1db23..dde8993091b6eb93c20db2f5b35e86fb670c40e6 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -8,14 +8,25 @@ - 快速开始 - 快速入门 - [开发准备](quick-start/start-overview.md) - - [使用eTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) - - [使用eTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) + - [使用ArkTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) + - [使用ArkTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) - [使用JS语言开发(FA模型)](quick-start/start-with-js-fa.md) - 开发基础知识 - [应用包结构说明(FA模型)](quick-start/package-structure.md) - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) + - 学习ArkTS语言 + - [初识ArkTS语言](quick-start/arkts-get-started.md) + - ArkTS语法(声明式UI) + - [基本UI描述](quick-start/arkts-basic-ui-description.md) + - 状态管理 + - [基本概念](quick-start/arkts-state-mgmt-concepts.md) + - [页面级变量的状态管理](quick-start/arkts-state-mgmt-page-level.md) + - [应用级变量的状态管理](quick-start/arkts-state-mgmt-application-level.md) + - [动态构建UI元素](quick-start/arkts-dynamic-ui-elememt-building.md) + - [渲染控制](quick-start/arkts-rendering-control.md) + - [使用限制与扩展](quick-start/arkts-restrictions-and-extensions.md) - 开发 - [Ability开发](ability/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/application-test/arkxtest-guidelines.md b/zh-cn/application-dev/application-test/arkxtest-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..410547a5d0ef493f9cee83b670b7a391023fb6e2 --- /dev/null +++ b/zh-cn/application-dev/application-test/arkxtest-guidelines.md @@ -0,0 +1,171 @@ +# 自动化测试框架使用指南 + + +## 概述 + +为支撑OpenHarmony操作系统的自动化测试活动开展,我们提供了支持JS/TS语言的单元及UI测试框架,支持开发者针对应用接口或系统接口进行单元测试,并且可基于UI操作进行UI自动化脚本的编写。 + +本指南重点介绍自动化测试框架的主要功能,同时介绍编写单元/UI自动化测试脚本的方法以及执行过程。 + + +### 简介 + +OpenHarmony自动化测试框架arkxtest,作为OpenHarmony工具集的重要组成部分,提供了OpenHarmony自动化脚本编写和运行的基础能力。编写方面提供了一系列支持测试脚本编写的API,包括了基础流程API、断言API以及UI操作相关的API,运行方面提供了识别测试脚本、调度执行测试脚本以及汇总测试脚本执行结果的能力。 + + +### 实现原理 + +框架重要分为两大部分:单元测试框架和UI测试框架。 + +- 单元测试框架 + + 单元测试框架是测试框架的基础底座,提供了最基本的用例识别、调度、执行及结果汇总的能力。主要功能如下图所示: + + ![](figures/UnitTest.PNG) + + 单元测试脚本的基础运行流程如下图所示,依赖aa test命令作为执行入口,该命令可具体参考[对应指南。](../ability/ability-delegator.md) + + ![](figures/TestFlow.PNG) + +- UI测试框架 + + UI测试框架主要对外提供了[UiTest API](../reference/apis/js-apis-uitest.md)供开发人员在对应测试场景调用,而其脚本的运行基础还是上面提到的单元测试框架。 + + UI测试框架的主要功能如下图所示: + + ![](figures/Uitest.PNG) + + +### 约束与限制 + +- UI测试框架的能力在OpenHarmony 3.1 release版本之后方可使用,历史版本不支持使用。 +- 单元测试框架的部分能力与其版本有关,具体能力与版本匹配信息可见代码仓中的[文档介绍](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_zh.md)。 + + +## 环境准备 + +### 环境要求 + +OpenHarmony自动化脚本的编写主要基于DevEco Studio,并建议使用3.0之后的版本进行脚本编写。 + +脚本执行需要PC连接OpenHarmony设备,如RK3568开发板等。 + +### 搭建环境 + +DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos.com/cn/develop/deveco-studio#download),并进行相关的配置动作。 + + +## 新建测试脚本 + +1. 在DevEco Studio中新建应用开发工程,其中ohos目录即为测试脚本所在的目录。 +2. 在工程目录下打开待测试模块下的ets文件,将光标置于代码中任意位置,单击**右键 > Show Context Actions** **> Create Ohos Test**或快捷键**Alt+enter** **> Create Ohos Test**创建测试类,更多指导请参考DevEco Studio中[指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001267284568)。 + +## 编写单元测试脚本 + +```TS +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' +import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +const delegator = abilityDelegatorRegistry.getAbilityDelegator() +export default function abilityTest() { + describe('ActsAbilityTest', function () { + it('testUiExample',0, async function (done) { + console.info("uitest: TestUiExample begin"); + //start tested ability + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ + console.info('Uitest, start ability finished:' + result) + }).catch(err => { + console.info('Uitest, start ability failed: ' + err) + }) + await sleep(1000); + //check top display ability + await delegator.getCurrentTopAbility().then((Ability)=>{ + console.info("get top ability"); + expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); + }) + done(); + }) + + function sleep(time) { + return new Promise((resolve) => setTimeout(resolve, time)); + } + }) +} +``` + +单元测试脚本需要包含如下基本元素: + +1、依赖导包,以便使用依赖的测试接口。 + +2、测试代码编写,主要编写测试代码的相关逻辑,如接口调用等。 + +3、断言接口调用,设置测试代码中的检查点,如无检查点,则不可认为一个完整的测试脚本。 + +## 编写UI测试脚本 + +UI测试脚本是在单元测试框架的基础上编写,主要就是增加了UI测试框架提供的接口调用,实现对应的测试逻辑。 + +下面的示例代码是在上面的测试脚本基础上增量编写,首先需要增加依赖导包,如下示例代码所示: + +```js +import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest' +``` + +然后是具体测试代码编写,场景较为简单,就是在启动的应用页面上进行点击操作,然后增加检查点检查用例。 + +```js +export default function abilityTest() { + describe('ActsAbilityTest', function () { + it('testUiExample',0, async function (done) { + console.info("uitest: TestUiExample begin"); + //start tested ability + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ + console.info('Uitest, start ability finished:' + result) + }).catch(err => { + console.info('Uitest, start ability failed: ' + err) + }) + await sleep(1000); + //check top display ability + await delegator.getCurrentTopAbility().then((Ability)=>{ + console.info("get top ability"); + expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); + }) + //ui test code + //init uidriver + var driver = await UiDriver.create(); + await driver.delayMs(1000); + //find button by text 'Next' + var button = await driver.findComponent(BY.text('Next')); + //click button + await button.click(); + await driver.delayMs(1000); + //check text + await driver.assertComponentExist(BY.text('after click')); + await driver.pressBack(); + done(); + }) + + function sleep(time) { + return new Promise((resolve) => setTimeout(resolve, time)); + } + }) +} +``` + +## 执行测试脚本 + +执行测试脚本可以直接在DevEco Studio中通过点击按钮执行,当前支持以下执行方式: + +1、测试包级别执行即执行测试包内的全部用例。 + +2、测试套级别执行即执行describe方法中定义的全部测试用例。 + +3、测试方法级别执行即执行指定it方法也就是单条测试用例。 + +![](figures/Execute.PNG) + +## 查看测试结果 + +测试执行完毕后可直接在DevEco Studio中查看测试结果,如下图示例所示: + +![](figures/TestResult.PNG) diff --git a/zh-cn/application-dev/application-test/figures/Execute.PNG b/zh-cn/application-dev/application-test/figures/Execute.PNG new file mode 100644 index 0000000000000000000000000000000000000000..49155c9b3406ea477e08273818e52fe026a62737 Binary files /dev/null and b/zh-cn/application-dev/application-test/figures/Execute.PNG differ diff --git a/zh-cn/application-dev/application-test/figures/TestFlow.PNG b/zh-cn/application-dev/application-test/figures/TestFlow.PNG new file mode 100644 index 0000000000000000000000000000000000000000..c1cd0d4e87070a5af4b7c8d72432a55585754551 Binary files /dev/null and b/zh-cn/application-dev/application-test/figures/TestFlow.PNG differ diff --git a/zh-cn/application-dev/application-test/figures/TestResult.PNG b/zh-cn/application-dev/application-test/figures/TestResult.PNG new file mode 100644 index 0000000000000000000000000000000000000000..300266842efab6da7a4f7469ab8c9e890f238b89 Binary files /dev/null and b/zh-cn/application-dev/application-test/figures/TestResult.PNG differ diff --git a/zh-cn/application-dev/application-test/figures/Uitest.PNG b/zh-cn/application-dev/application-test/figures/Uitest.PNG new file mode 100644 index 0000000000000000000000000000000000000000..2e84b95e4b0e61d78351e46a4ac2706e7847c6e2 Binary files /dev/null and b/zh-cn/application-dev/application-test/figures/Uitest.PNG differ diff --git a/zh-cn/application-dev/application-test/figures/UnitTest.PNG b/zh-cn/application-dev/application-test/figures/UnitTest.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a7af248d62e34bda8e02be095bcdb73c15e97a3f Binary files /dev/null and b/zh-cn/application-dev/application-test/figures/UnitTest.PNG differ 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..e2d21cff2ef3da0a87305f6f5f0ae257d638cf9c 100644 --- a/zh-cn/application-dev/device/usb-guidelines.md +++ b/zh-cn/application-dev/device/usb-guidelines.md @@ -163,4 +163,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 5a63c2fc33fab83623b8de9a1b1c8497d5790742..5b833306e08d8370f6d8433fdcc3dd91f9af01ce 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -1,28 +1,34 @@ # 音频播放开发指导 -## 场景介绍 +## 简介 -音频播放的主要工作是将音频数据转码为可听见的音频模拟信号并通过输出设备进行播放,同时对播放任务进行管理。 +音频播放的主要工作是将音频数据转码为可听见的音频模拟信号,并通过输出设备进行播放,同时对播放任务进行管理,包括开始播放、暂停播放、停止播放、释放资源、设置音量、跳转播放位置、获取轨道信息等功能控制。 -**图1** 音频播放状态机 +## 运作机制 + +该模块提供了音频播放状态变化示意图和音频播放外部模块交互图。 + +**图1** 音频播放状态变化示意图 ![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png) -**说明**:当前为Idle状态,设置src不会改变状态;且src设置成功后,不能再次设置其它src,需调用reset()接口后,才能重新设置src。 +**注意**:当前为Idle状态,设置src不会改变状态;且src设置成功后,不能再次设置其它src,需调用reset()接口后,才能重新设置src。 -**图2** 音频播放零层图 +**图2** 音频播放外部模块交互图 ![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png) -## 开发步骤 +**说明**:三方应用通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件,将软件解码后的音频数据输出至硬件接口层的音频HDI,实现音频播放功能。 + +## 开发指导 详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md#audioplayer) ### 全流程场景 -包含流程:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 +音频播放的全流程场景包含:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性) @@ -260,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 21fe9c01ad216b331e5c2e708397bfdce4672a4d..1da8cf5cc671fb009f9442008569a30b489c6582 100644 --- a/zh-cn/application-dev/media/audio-recorder.md +++ b/zh-cn/application-dev/media/audio-recorder.md @@ -1,26 +1,36 @@ # 音频录制开发指导 -## 场景介绍 +## 简介 -音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。它允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、文件路径等参数。 +音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。该模块允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、输出文件的路径等参数。 -**图1** 音频录制状态机 +## 运作机制 + +该模块提供了音频录制状态变化示意图和音频录制外部模块交互图。 + +**图1** 音频录制状态变化变化示意图 ![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png) -**图2** 音频录制零层图 +**图2** 音频录制外部模块交互图 ![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png) -## 开发步骤 +**说明**:三方录音应用或录音机通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件获取通过音频HDI捕获的音频数据,再通过软件编码输出编码封装后的音频数据保存至文件中,实现音频录制功能。 + +## 约束与限制 + +开发者在进行录制功能开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),权限配置相关内容可参考:[访问控制权限申请指导](../security/accesstoken-guidelines.md) + +## 开发指导 详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md#audiorecorder) ### 全流程场景 -包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。 +音频录制的全流程场景包含:创建实例,设置录制参数,开始录制,暂停录制,恢复录制,停止录制,释放资源等流程。 ```js import media from '@ohos.multimedia.media' @@ -190,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 040b9b479adce001468631ae6920321be06dc894..ea6044a54b0774ebd6954839a29b931874e0558a 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -1,17 +1,23 @@ # 视频播放开发指导 -## 场景介绍 +## 简介 -视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。 +视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务,包括开始播放、暂停播放、停止播放、资源释放、音量设置、跳转播放位置、设置倍数、获取轨道信息等功能控制。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。 -**图1** 视频播放状态机 +## 运作机制 + +该模块提供了视频播放状态变化示意图和视频播放外部模块交互图。 + +**图1** 视频播放状态变化示意图 ![zh-ch_image_video_state_machine](figures/zh-ch_image_video_state_machine.png) -**图2** 视频播放零层图 +**图2** 视频播放外部模块交互图 ![zh-ch_image_video_player](figures/zh-ch_image_video_player.png) +**说明**:三方应用通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件将软件解码后的音频数据,输出至音频HDI,和图形子系统将硬件接口层的解码HDI部件的解码后的图像数据,输出至显示HDI,实现视频播放功能。 + *注意:视频播放需要显示、音频、编解码等硬件能力。* 1. 三方应用从Xcomponent组件获取surfaceID。 @@ -31,13 +37,13 @@ | ts | 视频格式:H264/MPEG2/MPEG4 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P | | webm | 视频格式:VP8 音频格式:VORBIS | 主流分辨率,如1080P/720P/480P/270P | -## 开发步骤 +## 开发指导 详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md#videoplayer8) ### 全流程场景 -包含流程:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。 +视频播放的全流程场景包含:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。 VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性) @@ -445,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/media/video-recorder.md b/zh-cn/application-dev/media/video-recorder.md index 3be9de0cbb47ea787f1861fba9f32aa423fd935a..07b83bdf86217f38bfb47d8fa0850ed8349d4e96 100644 --- a/zh-cn/application-dev/media/video-recorder.md +++ b/zh-cn/application-dev/media/video-recorder.md @@ -1,24 +1,34 @@ # 视频录制开发指导 -## 场景介绍 +## 简介 -视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。 +视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能,包括开始录制、暂停录制、恢复录制、停止录制、释放资源等功能控制。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。 -**图1** 视频录制状态机 +## 运作机制 + +该模块提供了视频录制状态变化示意图和视频录制外部模块交互图。 + +**图1** 视频录制状态变化示意图 ![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png) -**图2** 视频录制零层图 +**图2** 视频录制外部模块交互图 ![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png) -## 开发步骤 +**说明**:三方相机应用或系统相机通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件通过音频HDI捕获的音频数据,再通过软件编码输出编码封装后的音频数据保存至文件中,和图形子系统通过视频HDI捕获的图像数据,再通过视频编码HDI编码,将编码后的图像数据保存至文件中,实现视频录制功能。 + +## 约束与限制 + +开发者在进行录制功能开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE)和相机权限(ohos.permission.CAMERA),权限配置相关内容可参考:[访问控制权限申请指导](../security/accesstoken-guidelines.md) + +## 开发指导 详细API含义可参考:[媒体服务API文档VideoRecorder](../reference/apis/js-apis-media.md#videorecorder9) ### 全流程场景 -包含流程:创建实例、设置录制参数、录制视频、暂停录制、恢复录制、停止录制、释放资源等流程。 +视频录制全流程场景包含:创建实例、设置录制参数、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。 ```js import media from '@ohos.multimedia.media' 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/Readme-CN.md b/zh-cn/application-dev/notification/Readme-CN.md index a85b267052b65b947b5cfd34d25ca940add25804..02b3a06e412f3617b2db876b92bf673e46d4914f 100644 --- a/zh-cn/application-dev/notification/Readme-CN.md +++ b/zh-cn/application-dev/notification/Readme-CN.md @@ -3,7 +3,4 @@ - [公共事件与通知概述](notification-brief.md) - [公共事件开发指导](common-event.md) - [通知开发指导](notification-guidelines.md) -- 后台代理提醒 - - [后台代理提醒开发概述](background-agent-scheduled-reminder-overview.md) - - [后台代理提醒开发指导](background-agent-scheduled-reminder-guide.md) - [调试助手使用指导](assistant-guidelines.md) \ 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 33af34aac4c374cfe452f20c8a40b6c3acd7b4b2..74f52e4b4073d12b41a8f0588127c6dc6a6447da 100644 --- a/zh-cn/application-dev/notification/common-event.md +++ b/zh-cn/application-dev/notification/common-event.md @@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; 2. 创建订阅者信息,详细的订阅者信息数据类型及包含的参数请见[CommonEventSubscribeInfo文档](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo)介绍。 ```js -private subscriber = null //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +//用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +private subscriber = null //订阅者信息 var subscribeInfo = { @@ -174,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-brief.md b/zh-cn/application-dev/notification/notification-brief.md index 9eaa31851c87ed6d9f35a1f32a37a797eef45f38..c1a2b37abcb08c2048d5f9d0f367e3c5651a337d 100644 --- a/zh-cn/application-dev/notification/notification-brief.md +++ b/zh-cn/application-dev/notification/notification-brief.md @@ -1,6 +1,6 @@ # 公共事件与通知开发概述 -公共事件与通知提供了应用程序向系统其他应用程序发布消息、接收来自系统或其他应用特定消息的能力,这些消息可以是新闻推送、广告通知或者预警信息。 +公共事件与通知提供了应用程序向系统其他应用程序发布消息、接收来自系统或其他应用特定消息的能力,这些消息可以是新闻推送、广告通知或者预警信息等。 CES(Common Event Service, 即公共事件服务)为应用程序提供发布、订阅及退订公共事件的能力。公共事件根据事件发送方不同可分为系统公共事件和自定义公共事件。 @@ -9,7 +9,7 @@ CES(Common Event Service, 即公共事件服务)为应用程序提供发布 - 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 公共事件包括:终端设备用户可感知的亮灭屏事件,以及系统关键服务发布的系统事件(例如:USB插拔,网络连接,系统升级)等。 - 自定义公共事件:由应用自身定义的期望特定订阅者可以接收到的公共事件,这些公共事件往往与应用自身的业务逻辑相关。 -ANS(Advanced Notification Service,即通知增强服务)为应用程序提供发布通知的能力。这些通知常见的使用场景如下: +ANS(Advanced Notification Service,即通知系统服务)为应用程序提供发布通知的能力。这些通知常见的使用场景如下: - 显示接收到的短消息、即时通讯消息等; - 显示应用的推送消息,如广告、版本更新、新闻通知等; 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 58a1eb04c23c9ef05efbc29c9ad77e0156525581..5e82e49502ed6523d297546178ce5973e585b881 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -2,8 +2,8 @@ - 快速入门 - [开发准备](start-overview.md) - - [使用eTS语言开发(Stage模型)](start-with-ets-stage.md) - - [使用eTS语言开发(FA模型)](start-with-ets-fa.md) + - [使用ArkTS语言开发(Stage模型)](start-with-ets-stage.md) + - [使用ArkTS语言开发(FA模型)](start-with-ets-fa.md) - [使用JS语言开发(FA模型)](start-with-js-fa.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 97% 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 index ad94463042f80ec79119a51d019a0d6d44aa7e25..922b4715478f37d49ed18a7ed4e4c98d54a3f981 100644 --- 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 @@ -1,6 +1,6 @@ -# 应用级变量的状态变量 +# 应用级变量的状态管理 -在前面的章节中,已经讲述了如何管理页面级变量的状态,本章将说明如何管理应用级变量的状态。 +在前面的章节中,已经讲述了如何管理页面级变量的状态,本章将说明如何管理应用级变量的状态,具体接口请参考[应用级变量的状态管理接口](../reference/arkui-ts/ts-state-management.md)。 ## AppStorage @@ -16,8 +16,6 @@ AppStorage的选择状态属性可以与不同的数据源或数据接收器同 默认情况下,AppStorage中的属性是可变的,AppStorage还可使用不可变(只读)属性。 - AppStorage的具体接口请参考[状态管理]() - ### @StorageLink装饰器 组件通过使用@StorageLink(key)装饰的状态变量,与AppStorage建立双向数据绑定,key为AppStorage中的属性键值。当创建包含@StorageLink的状态变量的组件时,该状态变量的值将使用AppStorage中的值进行初始化。在UI组件中对@StorageLink的状态变量所做的更改将同步到AppStorage,并从AppStorage同步到任何其他绑定实例中,如PersistentStorage或其他绑定的UI组件。 @@ -26,7 +24,7 @@ AppStorage的选择状态属性可以与不同的数据源或数据接收器同 组件通过使用@StorageProp(key)装饰的状态变量,将与AppStorage建立单向数据绑定,key标识AppStorage中的属性键值。当创建包含@StoageProp的状态变量的组件时,该状态变量的值将使用AppStorage中的值进行初始化。AppStorage中的属性值的更改会导致绑定的UI组件进行状态更新。 -## 示例 +### 示例 每次用户单击Count按钮时,this.varA变量值都会增加,此变量与AppStorage中的varA同步。每次用户单击当前语言按钮时,修改AppStorage中的languageCode,此修改会同步给this.lang变量。 @@ -93,11 +91,11 @@ Ability: 一个应用程序可以拥有多个Ability,一个Ability中的所 一个组件最多可以访问一个LocalStorage实例,一个LocalStorage对象可以分配给多个组件。 -## @LocalStorageLink装饰器 +### @LocalStorageLink装饰器 组件通过使用@LocalStorageLink(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立双向数据绑定。当创建包含@LocalStorageLink的状态变量的组件时,该状态变量的值将会使用LocalStorage中的值进行初始化。如果LocalStorage中未定义初始值,将使用@LocalStorageLink定义的初始值。在UI组件中对@LocalStorageLink的状态变量所做的更改将同步到LocalStorage中,并从LocalStorage同步到Ability下的组件中。 -## @LocalStorageProp装饰器 +### @LocalStorageProp装饰器 组件通过使用LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定。当创建包含@LocalStorageProp的状态变量的组件时,该状态变量的值将使用LocalStorage中的值进行初始化。LocalStorage中的属性值的更改会导致当前Ability下的所有UI组件进行状态更新。 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/quick-start/start-overview.md b/zh-cn/application-dev/quick-start/start-overview.md index 0834b0f2e2ea1b612027a5db9ebd43a854ead7c3..8b3da7d45a8f15236dcd3ed13f3fecceff8589f4 100644 --- a/zh-cn/application-dev/quick-start/start-overview.md +++ b/zh-cn/application-dev/quick-start/start-overview.md @@ -16,11 +16,11 @@ OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供应用UI开发所必需的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等。 -方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于eTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。 +方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于ArkTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。 | **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** | | -------- | -------- | -------- | -------- | -------- | -| 声明式开发范式 | eTS语言 | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | +| 声明式开发范式 | ArkTS语言 | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | | 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 | 更多UI框架的开发内容及指导,详见[UI开发](../ui/arkui-overview.md)。 @@ -36,7 +36,7 @@ Ability框架模型结构具有两种形态: - **Stage模型**:从API 9开始,Ability框架引入并支持使用Stage模型进行开发。更多Stage模型的内容详见[Stage模型综述](../ability/stage-brief.md)。 -FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持使用eTS语言进行开发。 +FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持使用ArkTS语言进行开发。 关于FA模型和Stage模型的整体架构和设计思想等更多区别,详见[Ability框架概述](../ability/ability-brief.md)。 @@ -49,4 +49,4 @@ FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持 2. 请参考[配置OpenHarmony SDK](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443),完成**DevEco Studio**的安装和开发环境配置。 -完成上述操作及基本概念的理解后,可参照[使用eTS语言进行开发(Stage模型)](start-with-ets-stage.md)、[使用eTS语言开发(FA模型)](start-with-ets-fa.md)、[使用JS语言开发(FA模型)](../quick-start/start-with-js-fa.md)中的任一章节进行下一步体验和学习。 +完成上述操作及基本概念的理解后,可参照[使用ArkTS语言进行开发(Stage模型)](start-with-ets-stage.md)、[使用ArkTS语言开发(FA模型)](start-with-ets-fa.md)、[使用JS语言开发(FA模型)](../quick-start/start-with-js-fa.md)中的任一章节进行下一步体验和学习。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-fa.md b/zh-cn/application-dev/quick-start/start-with-ets-fa.md index 67029223fecfe851231b29a186dd886cc48d0364..7dc4539e81e291b8b5f79774f4b69752588ad7bc 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-fa.md @@ -1,4 +1,4 @@ -# 使用eTS语言开发(FA模型) +# 使用ArkTS语言开发(FA模型) > **说明:** @@ -18,7 +18,7 @@ ![02](figures/02.png) > **说明:** - > DevEco Studio V3.0 Beta3及更高版本支持使用eTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 + > DevEco Studio V3.0 Beta3及更高版本支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > @@ -288,4 +288,4 @@ ![zh-cn_image_0000001363934577](figures/zh-cn_image_0000001363934577.png) -恭喜您已经使用eTS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 +恭喜您已经使用ArkTS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 33a404e1cc73a1cf5ee03e725cfc3ce8d4f8da81..8ff628f5a300a4257f6414431ef32d9e037e62f2 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -1,4 +1,4 @@ -# 使用eTS语言开发(Stage模型) +# 使用ArkTS语言开发(Stage模型) > **说明:** @@ -19,7 +19,7 @@ > **说明:** > - > 支持使用eTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 + > 支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > @@ -287,4 +287,4 @@ ![zh-cn_image_0000001311334972](figures/zh-cn_image_0000001311334972.png) -恭喜您已经使用eTS语言开发(Stage模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 +恭喜您已经使用ArkTS语言开发(Stage模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.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..ab65cc28da4dfd4b875d262a7afc708700fe83d8 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -148,8 +148,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-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 91854db0075a64f90dc1d2c6917716c2c50fc719..9fd24a19c160d1a0e7c8a40c44ded220e6d2c403 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开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。从API version 9开始,导入模块由@ohos.backgroundTaskManager迁移至@ohos.resourceschedule.backgroundTaskManager @@ -22,13 +22,13 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` -## backgroundTaskManager.requestSuspendDelay(deprecated) +## backgroundTaskManager.requestSuspendDelay7+(deprecated) requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo 后台应用申请延迟挂起。 -延迟挂起时间一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 +延迟挂起时间一般情况下默认值为180000毫秒,低电量(依据系统低电量广播)时默认值为60000毫秒。 > **说明:** 从API version 9开始废弃,建议使用[backgroundTaskManager.requestSuspendDelay](./js-apis-resourceschedule-backgroundTaskManager.md/#backgroundtaskmanagerrequestsuspenddelay9) > @@ -56,9 +56,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); ``` @@ -79,7 +79,7 @@ getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------- | ---- | ---------------------------------------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | | callback | AsyncCallback<number> | 是 | 指定的callback回调方法。用于返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 | **示例**: @@ -87,8 +87,8 @@ getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; - 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 { @@ -113,7 +113,7 @@ getRemainingDelayTime(requestId: number): Promise<number> **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | **返回值**: | 类型 | 说明 | @@ -122,10 +122,8 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - 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); @@ -148,14 +146,12 @@ cancelSuspendDelay(requestId: number): void **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | **示例**: ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - let id = 1; - backgroundTaskManager.cancelSuspendDelay(id); + let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId); ``` @@ -182,6 +178,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'; @@ -209,11 +208,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+(deprecated) startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> @@ -242,6 +278,9 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | Promise\ | 使用Promise形式返回结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -261,13 +300,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+(deprecated) @@ -289,6 +360,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'; @@ -305,6 +379,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+(deprecated) stopBackgroundRunning(context: Context): Promise<void> @@ -328,6 +423,9 @@ stopBackgroundRunning(context: Context): Promise<void> | Promise\ | 使用Promise形式返回结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -340,11 +438,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+(deprecated) applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest9)): void -向系统申请能效资源,使用boolean形式返回结果。 +向系统申请或释放能效资源,使用boolean形式返回结果。 +通过EfficiencyResourcesRequest参数中的isApply变量,设置是申请还是释放。 +应用使用此接口,需要向应用中心申请获得相应特权。 进程和它所属的应用可以同时申请某一类资源,例如CPU资源,但是应用释放资源的时候会将进程的资源一起释放。 > **说明:** 从API version 9开始废弃,建议使用[backgroundTaskManager.applyEfficiencyResources](./js-apis-resourceschedule-backgroundTaskManager.md/#backgroundtaskmanagerapplyefficiencyresources9) @@ -368,6 +485,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; let request = { resourceTypes: backgroundTaskManager.ResourceType.CPU, + // 如果将isApply置为false,则表示释放资源 isApply: true, timeOut: 0, reason: "apply", @@ -387,6 +505,7 @@ try { resetAllEfficiencyResources(): void 释放所有已经申请的资源。 +应用使用此接口,需要向应用中心申请获得相应特权。 > **说明:** 从API version 9开始废弃,建议使用[backgroundTaskManager.resetAllEfficiencyResources](./js-apis-resourceschedule-backgroundTaskManager.md/#backgroundtaskmanagerresetallefficiencyresources9) > 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-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-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index 5bad8bf8c1cb69f43ae5cb9a469f70fb3572a261..1d7ecedb9bf69cf520049f33f1a3bfd780c1243b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -20,9 +20,9 @@ getCameraManager(context: Context, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | ---------------------------------- | -| context | Context | 是 | 应用上下文。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ---------------------------- | +| context | Context | 是 | 应用上下文。 | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 | **示例:** @@ -30,7 +30,7 @@ getCameraManager(context: Context, callback: AsyncCallback): voi ```js camera.getCameraManager(context, (err, cameraManager) => { if (err) { - console.error('Failed to get the CameraManager instance ${err.message}'); + console.error(`Failed to get the CameraManager instance ${err.message}`); return; } console.log('Callback returned with the CameraManager instance'); @@ -53,8 +53,8 @@ getCameraManager(context: Context): Promise **返回值:** -| 类型 | 说明 | -| ----------------------------------------- | ----------------------------------------- | +| 类型 | 说明 | +| ----------------------------------------- | ----------------------------------- | | Promise<[CameraManager](#cameramanager)\> | 使用Promise的方式获取一个相机管理器实例。 | **示例:** @@ -73,179 +73,172 @@ camera.getCameraManager(context).then((cameraManager) => { | 名称 | 值 | 说明 | | ------------------------- | ---- | ------------ | -| CAMERA_STATUS_APPEAR | 0 | 相机存在。 | -| CAMERA_STATUS_DISAPPEAR | 1 | 相机不存在。 | -| CAMERA_STATUS_AVAILABLE | 2 | 相机就绪。 | -| CAMERA_STATUS_UNAVAILABLE | 3 | 相机未就绪。 | +| CAMERA_STATUS_APPEAR | 0 | 新的相机出现。 | +| CAMERA_STATUS_DISAPPEAR | 1 | 相机被移除。 | +| CAMERA_STATUS_AVAILABLE | 2 | 相机可用。 | +| CAMERA_STATUS_UNAVAILABLE | 3 | 相机不可用。 | +## Profile -## CameraPosition - -枚举,相机方向。 +相机配置信息项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| --------------------------- | ---- | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | 未指定方向相机。 | -| CAMERA_POSITION_BACK | 1 | 后置相机。 | -| CAMERA_POSITION_FRONT | 2 | 前置相机。 | +| 名称 | 类型 | 只读 | 说明 | +| -------- | ----------------------------- |---- | ------------- | +| format | [CameraFormat](#cameraformat) | 是 | 输出格式。 | +| size | [Size](#size) | 是 | 分辨率。 | -## CameraType +## FrameRateRange -枚举,相机类型。 +帧率范围。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ----------------------- | ---- | ---------------- | -| CAMERA_TYPE_UNSPECIFIED | 0 | 未指定相机类型。 | -| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | -| CAMERA_TYPE_ULTRA_WIDE | 2 | 超级广角相机。 | -| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | -| CAMERA_TYPE_TRUE_DEPTH | 4 | 深度相机。 | - +| 名称 | 类型 | 只读 | 说明 | +| -------- | ----------------------------- |---- | ------------- | +| min | number | 是 | 最小帧率。 | +| max | number | 是 | 最大帧率。 | -## ConnectionType +## VideoProfile -枚举,相机连接类型。 +视频配置信息项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ---------------------------- | ---- | ------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。 | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | 外置USB相机。 | -| CAMERA_CONNECTION_REMOTE | 2 | 分布式相机。 | +| 名称 | 类型 | 只读 | 说明 | +| ------------------------- | ----------------------------------------- | --- |----------- | +| frameRateRange | [FrameRateRange](#frameraterange) | 是 | 帧率范围。 | -## Size +## CameraOutputCapability -用于表示相机预览、照片、视频支持的尺寸大小。 +相机输出能力项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ | ---- | ---- | ------------ | -| height | string | 是 | 是 | 图像的高度。 | -| width | number | 是 | 是 | 图像的宽度。 | +| 名称 | 类型 | 只读 | 说明 | +| ----------------------------- | -------------------------------------------------- | --- |------------------- | +| previewProfiles | Array<[Profile](#profile)\> | 是 | 支持的预览配置信息。 | +| photoProfiles | Array<[Profile](#profile)\> | 是 | 支持的拍照配置信息。 | +| videoProfiles | Array<[VideoProfile](#videoprofile)\> | 是 | 支持的录像配置信息。 | +| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | 支持的metadata流类型信息。| ## CameraManager 相机管理器类,使用前需要通过getCameraManager获取相机管理实例。 -### getCameras +### getSupportedCameras -getCameras(callback: AsyncCallback\>): void +getSupportedCameras(callback: AsyncCallback\>): void -异步获取设备支持的相机列表,通过注册回调函数获取结果。 +获取支持指定的相机设备对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | **示例:** ```js -cameraManager.getCameras((err, cameras) => { +cameraManager.getSupportedCameras((err, cameras) => { if (err) { - console.error('Failed to get the cameras. ${err.message}'); + console.error(`Failed to get the cameras. ${err.message}`); return; } - console.log('Callback returned with an array of supported cameras: ' + cameras.length); + console.log(`Callback returned with an array of supported cameras: ${cameras.length}`); }) ``` -### getCameras +### getSupportedCameras -getCameras(): Promise\> +getSupportedCameras(): Promise\> -异步获取设备支持的相机列表,通过Promise获取结果。 +获取支持指定的相机设备对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ----------------------------------- | ----------------------------- | -| Promise\> | 使用promise获取支持相机列表。 | +| 类型 | 说明 | +| ----------------------------------------------- | ------------------------- | +| Promise\> | 使用promise获取支持相机列表。 | **示例:** ```js -cameraManager.getCameras().then((cameraArray) => { - console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); +cameraManager.getSupportedCameras().then((cameraArray) => { + console.log(`Promise returned with an array of supported cameras: ${cameraArray.length}`); }) ``` -### createCameraInput - -createCameraInput(cameraId: string, callback: AsyncCallback): void +### getSupportedOutputCapability -使用相机ID异步创建CameraInput实例,通过注册回调函数获取结果。 +getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void -**需要权限:** ohos.permission.CAMERA +查询相机设备在模式下支持的输出能力,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| cameraId | string | 是 | 指定相机ID。 | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------ |--------------------------------------------------------------- | -- | -------------------------- | +| CameraDevice | [CameraDevice](#cameradevice) | 是 | 相机设备。 | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | 是 | 使用callback方式获取相机输出能力。 | **示例:** ```js -cameraManager.createCameraInput(cameraId, (err, cameraInput) => { +cameraManager.getSupportedOutputCapability(cameradevice, (err, cameras) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error(`Failed to get the cameras. ${err.message}`); return; } - console.log('Callback returned with the CameraInput instance.'); + console.log('Callback returned with an array of supported outputCapability'); }) ``` -### createCameraInput - -createCameraInput(cameraId: string): Promise +### getSupportedOutputCapability -使用相机ID异步创建CameraInput实例,通过Promise获取结果。 +getSupportedOutputCapability(camera:CameraDevice): Promise -**需要权限:** ohos.permission.CAMERA +查询相机设备在模式下支持的输出能力,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------ | -| cameraId | string | 是 | 指定相机ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameradevice) | 是 | 相机设备。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | +| 类型 | 说明 | +| -------------------------------------------------------------- | ----------------------------- | +| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | 使用Promise的方式获取结果,返回相机输出能力。 | + **示例:** ```js -cameraManager.createCameraInput(cameraId).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapability) => { + console.log('Promise returned with an array of supported outputCapability'); }) ``` ### createCameraInput -createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void +createCameraInput(camera: CameraDevice, callback: AsyncCallback): void -使用相机位置和相机类型异步创建CameraInput实例,通过注册回调函数获取结果。 +使用CameraDevice对象异步创建CameraInput实例,通过注册回调函数获取结果。 + +此接口为系统接口。 **需要权限:** ohos.permission.CAMERA @@ -253,29 +246,30 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| type | [CameraType](#cameratype) | 是 | 相机类型。 | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| camera | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { +cameraManager.createCameraInput(camera, (err, cameraInput) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error(`Failed to create the CameraInput instance. ${err.message}`); return; } - console.log('Callback returned with the CameraInput instance'); + console.log('Callback returned with the CameraInput instance.'); }) ``` ### createCameraInput -createCameraInput(position: CameraPosition, type: CameraType): Promise +createCameraInput(camera: CameraDevice): Promise -使用相机位置和相机类型异步创建CameraInput实例,通过Promise获取结果。 +使用CameraDevice对象异步创建CameraInput实例,通过Promise获取结果。 + +此接口为系统接口。 **需要权限:** ohos.permission.CAMERA @@ -283,786 +277,696 @@ createCameraInput(position: CameraPosition, type: CameraType): Promise | 使用Promise的方式获取CameraInput的实例。 | **示例:** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance.'); +cameraManager.createCameraInput(camera).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### on('cameraStatus') +### createCameraInput -on(type: 'cameraStatus', callback: AsyncCallback): void +createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void -监听相机的状态变化,通过注册回调函数获取相机的状态变化。 +根据相机位置和类型创建CameraInput实例,通过注册回调函数获取结果。 + +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------------- | -| type | string | 是 | 监听事件,固定为'cameraStatus',即相机状态变化事件。 | -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取相机状态变化信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| type | [CameraType](#cameratype) | 是 | 相机类型。 | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** ```js -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { - console.error('Failed to get cameraStatus callback. ${err.message}'); + console.error(`Failed to create the CameraInput instance. ${err.message}`); return; } - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); + console.log('Callback returned with the CameraInput instance'); }) ``` -## Camera - -调用[camera.getCameraManager](#cameragetcameramanager)后,将返回Camera实例,包括相机ID、位置、类型、连接类型等相机相关的元数据。 +### createCameraInput -**系统能力:** SystemCapability.Multimedia.Camera.Core。 +createCameraInput(position: CameraPosition, type:CameraType ): Promise -| 名称 | 类型 | 只读 | 说明 | -| -------------- | --------------------------------- | ---- | -------------- | -| cameraId | string | 是 | 相机ID。 | -| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | -| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。 | +根据相机位置和类型创建CameraInput实例,通过Promise获取结果。 -**示例:** +此接口为系统接口。 -```js -async function getCameraInfo("cameraId") { - var cameraManager = await camera.getCameraManager(context); - var cameras = await cameraManager.getCameras(); - var cameraObj = cameras[0]; - var cameraId = cameraObj.cameraId; - var cameraPosition = cameraObj.cameraPosition; - var cameraType = cameraObj.cameraType; - var connectionType = cameraObj.connectionType; -} -``` +**需要权限:** ohos.permission.CAMERA -## CameraStatusInfo +**系统能力:** SystemCapability.Multimedia.Camera.Core -相机管理器回调返回的接口实例,表示相机状态信息。 +**参数:** -**系统能力:** SystemCapability.Multimedia.Camera.Core。 +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------- | ---- | ------------ | +| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| type | [CameraType](#cameratype) | 是 | 相机类型。 | -| 名称 | 类型 | 说明 | -| ------ | ----------------------------- | ---------- | -| camera | [Camera](#camera) | 相机信息。 | -| status | [CameraStatus](#camerastatus) | 相机状态。 | +**返回值:** +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------ | +| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | -## CameraInput +**示例:** -相机输入类。在使用该类的方法前,需要先构建一个CameraInput实例。 +```js +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); +}) +``` -### getCameraId +### createPreviewOutput -getCameraId(callback: AsyncCallback\): void +createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -异步获取该CameraInput实例的相机ID,通过注册回调函数获取结果。 +创建预览输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback | 是 | 回调函数,用于获取相机ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ------------------------------- | +| 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 -cameraInput.getCameraId((err, cameraId) => { +cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { if (err) { - console.error('Failed to get the camera ID. ${err.message}'); + console.error(`Failed to gcreate previewOutput. ${err.message}`); return; } - console.log('Callback returned with the camera ID: ' + cameraId); + console.log('Callback returned with previewOutput created.'); }) ``` -### getCameraId +### createPreviewOutput -getCameraId(): Promise +createPreviewOutput(profile: Profile, surfaceId: string): Promise -异步获取该CameraInput实例的相机ID,通过Promise获取结果。 +创建预览输出对象,通过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 | 使用Promise的方式获取相机ID。 | +| 类型 | 说明 | +| ---------------------------------------- | ---------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取PreviewOutput的实例。 | **示例:** ```js -cameraInput.getCameraId().then((cameraId) => { - console.log('Promise returned with the camera ID:' + cameraId); +cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => { + console.log('Promise returned with previewOutput created.'); }) ``` +### createPhotoOutput -### hasFlash - -hasFlash(callback: AsyncCallback): void +createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -判断设备是否支持闪光灯,通过注册回调函数获取结果。 +创建拍照输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| profile | [Profile](#profile) | 是 | 支持的拍照配置信息。 | +| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的SurfaceID。| +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | **示例:** ```js -cameraInput.hasFlash((err, status) => { +cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { if (err) { - console.error('Failed to check whether the device has flash light. ${err.message}'); + console.error(`Failed to create photoOutput. ${err.message}`); return; } - console.log('Callback returned with flash light support status: ' + status); + console.log('Callback returned with photoOutput created.'); }) ``` -### hasFlash +### createPhotoOutput -hasFlash(): Promise +createPhotoOutput(profile: Profile, surfaceId: string): Promise -判断设备是否支持闪光灯,通过Promise获取结果。 +创建拍照输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ----------- | +| profile | [Profile](#profile) | 是 | 支持的拍照配置信息。 | +| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的SurfaceID。| + **返回值:** -| 类型 | 说明 | -| ----------------- | ------------------------------------------------------- | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | +| 类型 | 说明 | +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput的实例。 | **示例:** ```js -cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); +cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { + console.log('Promise returned with photoOutput created.'); }) ``` -### isFlashModeSupported +### createVideoOutput -isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void +createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void -判断设备是否支持指定闪光灯模式,通过注册回调函数获取结果。 +创建录像输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------------------------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ------------------------------ | +| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息。 | +| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的SurfaceID。| +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { if (err) { - console.error('Failed to check whether the flash mode is supported. ${err.message}'); + console.error(`Failed to create videoOutput. ${err.message}`); return; } - console.log('Callback returned with the flash mode support status: ' + status); + console.log('Callback returned with an array of supported outputCapability' ); }) ``` -### isFlashModeSupported +### createVideoOutput -isFlashModeSupported(flashMode: FlashMode): Promise +createVideoOutput(profile: VideoProfile, surfaceId: string): Promise -判断设备是否支持指定闪光灯模式,通过Promise获取结果。 +创建录像输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ---------- | +| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息。 | +| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的SurfaceID。| **返回值:** -| 类型 | 说明 | -| ----------------- | ------------------------------------------------------------ | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | +| 类型 | 说明 | +| ------------------------------------- | -------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | 使用Promise的方式获取videoOutput的实例。 | **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { - console.log('Promise returned with flash mode support status.' + status); +cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { + console.log('Promise returned with videoOutput created.'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void - -设置闪光灯模式,通过注册回调函数获取结果。 +### createMetadataOutput -进行设置之前,需要先检查: +createMetadataOutput(metadataObjectTypes:Array, callback: AsyncCallback): void -1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 -2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 +创建metadata流输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ------------------------ | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | -------------------------------------------------- | --- | ---------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息。 | +| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | 是 | 回调函数,用于获取MetadataOutput实例。 | **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { if (err) { - console.error('Failed to set the flash mode ${err.message}'); + console.error(`Failed to create metadataOutput. ${err.message}`); return; } - console.log('Callback returned with the successful execution of setFlashMode.'); + console.log('Callback returned with metadataOutput created.'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode): Promise - -设置闪光灯模式,通过Promise获取结果。 +### createMetadataOutput -进行设置之前,需要先检查: +createMetadataOutput(metadataObjectTypes:Array): Promise -1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 -2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 +创建metadata流输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | -------------------------------------------------- | --- | -------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ------------------------------------------ | ----------------------------------------- | +| Promise<[MetadataOutput](#metadataoutput)\> | 使用Promise的方式获取MetadataOutput的实例。 | **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFlashMode.'); +cameraManager.createMetadataOutput().then((metadataoutput) => { + console.log('Promise returned with metadataOutput created.'); }) ``` -### getFlashMode +### createCaptureSession -getFlashMode(callback: AsyncCallback): void +createCaptureSession(callback: AsyncCallback): void -获取当前设备的闪光灯模式,通过注册回调函数获取结果。 +创建CaptureSession实例,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | ----------------------------------------- | ----------- | ---------------------------- | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取拍照会话实例。 | **示例:** ```js -cameraInput.getFlashMode((err, flashMode) => { +cameraManager.createCaptureSession((err, capturesession) => { if (err) { - console.error('Failed to get the flash mode ${err.message}'); + console.error(`Failed to create captureSession. ${err.message}`); return; } - console.log('Callback returned with current flash mode: ' + flashMode); + console.log('Callback returned with captureSession created.'); }) ``` -### getFlashMode +### createCaptureSession -getFlashMode(): Promise +createCaptureSession(): Promise -获取当前设备的闪光灯模式,通过Promise获取结果。 +创建CaptureSession实例,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| --------------------------------- | --------------------------------------- | -| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | +| 类型 | 说明 | +| ------------------------------------------- | ---------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession的实例。 | **示例:** ```js -cameraInput.getFlashMode().then((flashMode) => { - console.log('Promise returned with current flash mode : ' + flashMode); +cameraManager.createCaptureSession().then((capturesession) => { + console.log('Promise returned with captureSession created.'); }) ``` -### isFocusModeSupported +### on('cameraStatus') -isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void +on(type: 'cameraStatus', callback: AsyncCallback): void -判断设备是否支持指定的焦距模式,通过注册回调函数获取结果。 +镜头状态回调,通过注册回调函数获取相机的状态变化。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | --------- | +| type | string | 是 | 监听事件,固定为'cameraStatus',即镜头状态变化事件。 | +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取镜头状态变化信息。 | **示例:** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { - console.error('Failed to check whether the focus mode is supported. ${err.message}'); + console.error(`Failed to get cameraStatus callback. ${err.message}`); return; } - console.log('Callback returned with the focus mode support status: ' + status); + console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.log(`status: ${cameraStatusInfo.status}`); }) ``` -### isFocusModeSupported +## CameraStatusInfo -isFocusModeSupported(afMode: FocusMode): Promise +相机管理器回调返回的接口实例,表示相机状态信息。 -判断设备是否支持指定的焦距模式,通过Promise获取结果。 +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -**系统能力:** SystemCapability.Multimedia.Camera.Core +| 名称 | 类型 | 说明 | +| ------ | ----------------------------- | ---------- | +| camera | [CameraDevice](#cameradevice) | 相机信息。 | +| status | [CameraStatus](#camerastatus) | 相机状态。 | -**参数:** +## CameraPosition -| 名称 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +枚举,相机位置。 -**返回值:** +**系统能力:** SystemCapability.Multimedia.Camera.Core -| 类型 | 说明 | -| ----------------- | ----------------------------------------------------------- | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | +| 名称 | 值 | 说明 | +| --------------------------- | ---- | -------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | 相机位置未指定。 | +| CAMERA_POSITION_BACK | 1 | 后置相机。 | +| CAMERA_POSITION_FRONT | 2 | 前置相机。 | -**示例:** +## CameraType -```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { - console.log('Promise returned with focus mode support status.' + status); -}) -``` +枚举,相机类型。 -### setFocusMode +**系统能力:** SystemCapability.Multimedia.Camera.Core -setFocusMode(afMode: FocusMode, callback: AsyncCallback): void +| 名称 | 值 | 说明 | +| ----------------------- | ---- | -------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | 相机类型未指定。 | +| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | +| CAMERA_TYPE_ULTRA_WIDE | 2 | 超广角相机。 | +| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | +| CAMERA_TYPE_TRUE_DEPTH | 4 | 带景深信息的相机。 | -设置焦距模式,通过注册回调函数获取结果。 +## ConnectionType -进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 +枚举,相机连接类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** +| 名称 | 值 | 说明 | +| ---------------------------- | ---- | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。 | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | USB连接的相机。 | +| CAMERA_CONNECTION_REMOTE | 2 | 远程连接的相机。 | -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ------------------------ | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +## CameraDevice + +相机设备信息。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 只读 | 说明 | +| -------------- | --------------------------------- | ---- | ---------- | +| cameraId | string | 是 | CameraDevice对象| +| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | +| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。 | **示例:** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { - if (err) { - console.error('Failed to set the focus mode ${err.message}'); - return; - } - console.log('Callback returned with the successful execution of setFocusMode.'); -}) +async function getCameraInfo("cameraId") { + let cameraManager = await camera.getCameraManager(context); + let cameras = await cameraManager.getSupportedCameras(); + let cameraObj = cameras[0]; + let cameraId = cameraObj.cameraId; + let cameraPosition = cameraObj.cameraPosition; + let cameraType = cameraObj.cameraType; + let connectionType = cameraObj.connectionType; +} ``` -### setFocusMode +## Size -setFocusMode(afMode: FocusMode): Promise +枚举,输出能力查询。 -设置焦距模式,通过Promise获取结果。 +**系统能力:** SystemCapability.Multimedia.Camera.Core -进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------ | +| height | number | 是 | 是 | 图像尺寸高(像素)。 | +| width | number | 是 | 是 | 图像尺寸宽(像素)。 | + +## Point + +枚举,点坐标用于对焦、曝光配置。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| x | number | 是 | 点的x坐标。 | +| y | number | 是 | 点的y坐标。 | -| 名称 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +## CameraFormat -**返回值:** +枚举,输出格式。 -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +**系统能力:** SystemCapability.Multimedia.Camera.Core -**示例:** +| 名称 | 默认值 | 说明 | +| ----------------------- | --------- | ------------ | +| CAMERA_FORMAT_RGBA_8888 | 3 | RGB格式的图片。 | +| CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP格式的图片。 | +| CAMERA_FORMAT_JPEG | 2000 | JPEG格式的图片。 | -```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFocusMode.'); -}) -``` +## CameraInput -### getFocusMode +会话中[CaptureSession](#capturesession)使用的相机信息。 -getFocusMode(callback: AsyncCallback): void +### open -获取当前设备的焦距模式,通过注册回调函数获取结果。 +open\(callback: AsyncCallback\): void + +打开相机,通过注册回调函数获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.getFocusMode((err, afMode) => { +cameraInput.open((err) => { if (err) { - console.error('Failed to get the focus mode ${err.message}'); + console.error(`Failed to open the camera. ${err.message}`); return; } - console.log('Callback returned with current focus mode: ' + afMode); + console.log('Callback returned with camera opened.'); }) ``` -### getFocusMode +### open -getFocusMode(): Promise +open(): Promise -获取当前设备的焦距模式,通过Promise获取结果。 +打开相机,通过Promise获取相机的状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------------------- | -| Promise | 使用Promise的方式获取当前的焦距模式。 | +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -cameraInput.getFocusMode().then((afMode) => { - console.log('Promise returned with current focus mode : ' + afMode); +cameraInput.open().then(() => { + console.log('Promise returned with camera opened.'); }) ``` -### getZoomRatioRange +### close -getZoomRatioRange\(callback: AsyncCallback\>\): void +close\(callback: AsyncCallback\): void -获取可变焦距比范围,通过注册回调函数获取结果。 +关闭相机,通过注册回调函数获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------ | ---- | ------------------------ | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取可变焦距比范围,返回的数组包括其最小值和最大值。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { +cameraInput.close((err) => { if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); + console.error(`Failed to close the cameras. ${err.message}`); return; } - console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); + console.log('Callback returned with camera closed.'); }) ``` -### getZoomRatioRange +### close -getZoomRatioRange\(\): Promise\> +close(): Promise -获取可变焦距比范围,通过Promise获取结果。 +关闭相机,通过Promise获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ------------------------ | ------------------------------------------- | -| Promise\> | 使用Promise的方式获取当前的可变焦距比范围,返回的数组包括其最小值和最大值。 | +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { - console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); +cameraInput.close().then(() => { + console.log('Promise returned with camera closed.'); }) ``` -### setZoomRatio +### release -setZoomRatio(zoomRatio: number, callback: AsyncCallback): void +release\(callback: AsyncCallback\): void -设置可变焦距比,通过注册回调函数获取结果。 +释放资源,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | -------------------- | ---- | ------------------------ | -| zoomRatio | number | 是 | 可变焦距比。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.setZoomRatio(1, (err) => { +cameraInput.release((err) => { if (err) { - console.error('Failed to set the zoom ratio value ${err.message}'); + console.error(`Failed to release the CameraInput instance ${err.message}`); return; } - console.log('Callback returned with the successful execution of setZoomRatio.'); -}) + console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); +}); ``` -### setZoomRatio +### release -setZoomRatio(zoomRatio: number): Promise +release(): Promise -设置可变焦距比,通过Promise获取结果。 +释放资源,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ------------ | -| zoomRatio | number | 是 | 可变焦距比。 | - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -cameraInput.setZoomRatio(1).then(() => { - console.log('Promise returned with the successful execution of setZoomRatio.'); +cameraInput.release().then(() => { + console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); }) ``` -### getZoomRatio +### on('error') -getZoomRatio(callback: AsyncCallback): void +on(type: 'error', camera:CameraDevice, callback: ErrorCallback): void -获取当前的可变焦距比,通过注册回调函数获取结果。 +监听CameraInput的错误事件,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -cameraInput.getZoomRatio((err, zoomRatio) => { - if (err) { - console.error('Failed to get the zoom ratio ${err.message}'); - return; - } - console.log('Callback returned with current zoom ratio: ' + zoomRatio); -}) -``` - -### getZoomRatio - -getZoomRatio(): Promise - -获取当前的可变焦距比,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| ---------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -cameraInput.getZoomRatio().then((zoomRatio) => { - console.log('Promise returned with current zoom ratio : ' + zoomRatio); -}) -``` - -### release - -release\(callback: AsyncCallback\): void - -释放相机实例,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -cameraInput.release((err) => { - if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); -``` - -### release - -release(): Promise - -释放相机实例,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -cameraInput.release().then(() => { - console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); -}) -``` - -### on('focusStateChange') - -on(type: 'focusStateChange', callback: AsyncCallback): void - -监听焦距的状态变化,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------- | :--- | :------------------------------------------------------- | -| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | -| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | - -**示例:** - -```js -cameraInput.on('focusStateChange', (focusState) => { - console.log('Focus state : ' + focusState); -}) -``` - -### on('error') - -on(type: 'error', callback: ErrorCallback): void - -监听CameraInput的错误事件,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------------------- | :--- | :----------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 | -| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | --- | ------------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 | +| camera | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 | +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 | **示例:** ```js cameraInput.on('error', (cameraInputError) => { - console.log('Camera input error code: ' + cameraInputError.code); + console.log(`Camera input error code: ${cameraInputError.code}`); }) ``` -## CameraInputErrorCode +## CameraInputErrorCode -枚举,CameraInput的错误码。 +枚举,[CameraInput](#camerainput)错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_NO_PERMISSION | 0 | 没有权限。 | +| ERROR_DEVICE_PREEMPTED | 1 | 相机被抢占。 | +| ERROR_DEVICE_DISCONNECTED | 2 | 相机断开连接。 | +| ERROR_DEVICE_IN_USE | 3 | 相机正在使用。 | +| ERROR_DRIVER_ERROR | 4 | 驱动错误。 | -## CameraInputError +## CameraInputError -CameraInput错误对象。 +[CameraInput](#camerainput)错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------- | -------------------------- | +| 名称 | 类型 | 说明 | +| ---- | --------------------------------------------- | --------------------- | | code | [CameraInputErrorCode](#camerainputerrorcode) | CameraInput中的错误码。 | @@ -1072,96 +976,67 @@ CameraInput错误对象。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| ---------------------- | ---- | ------------ | +| 名称 | 值 | 说明 | +| ---------------------- | ---- | ---------- | | FLASH_MODE_CLOSE | 0 | 闪光灯关闭。 | -| FLASH_MODE_OPEN | 1 | 闪光灯开启。 | +| FLASH_MODE_OPEN | 1 | 闪光灯打开。 | | FLASH_MODE_AUTO | 2 | 自动闪光灯。 | | FLASH_MODE_ALWAYS_OPEN | 3 | 闪光灯常亮。 | -## FocusMode +## ExposureMode -枚举,焦距模式。 +枚举,曝光模式。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| -------------------------- | ---- | ------------------ | -| FOCUS_MODE_MANUAL | 0 | 手动变焦模式。 | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动变焦模式。 | -| FOCUS_MODE_AUTO | 2 | 自动变焦模式。 | -| FOCUS_MODE_LOCKED | 3 | 定焦模式。 | +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | ----------- | +| EXPOSURE_MODE_LOCKED | 0 | 锁定曝光模式。 | +| EXPOSURE_MODE_AUTO | 1 | 自动曝光模式。 | +| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | 连续自动曝光。 | -## FocusState +## FocusMode -枚举,焦距状态。 +枚举,焦距模式。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| --------------------- | ---- | ------------ | -| FOCUS_STATE_SCAN | 0 | 扫描状态。 | -| FOCUS_STATE_FOCUSED | 1 | 相机已对焦。 | -| FOCUS_STATE_UNFOCUSED | 2 | 相机未对焦。 | - -## camera.createCaptureSession - -createCaptureSession\(context: Context, callback: AsyncCallback\): void - -获取CaptureSession实例,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------- | ---- | -------------------------------------- | -| context | Context | 是 | 应用上下文。 | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取CaptureSession实例。 | - -**示例:** - -```js -camera.createCaptureSession((context), (err, captureSession) => { - if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); - return; - } - console.log('Callback returned with the CaptureSession instance.' + captureSession); -}); -``` - -## camera.createCaptureSession +| 名称 | 值 | 说明 | +| -------------------------- | ---- | ------------ | +| FOCUS_MODE_MANUAL | 0 | 手动对焦。 | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动对焦。 | +| FOCUS_MODE_AUTO | 2 | 自动变焦。 | +| FOCUS_MODE_LOCKED | 3 | 对焦锁定。 | -createCaptureSession(context: Context\): Promise; - -获取CaptureSession实例,通过Promise获取结果。 +## FocusState -**系统能力:** SystemCapability.Multimedia.Camera.Core +枚举,焦距状态。 -**参数:** +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | ------------ | -| context | Context | 是 | 应用上下文。 | +| 名称 | 值 | 说明 | +| --------------------- | ---- | --------- | +| FOCUS_STATE_SCAN | 0 | 触发对焦。 | +| FOCUS_STATE_FOCUSED | 1 | 对焦成功。 | +| FOCUS_STATE_UNFOCUSED | 2 | 未完成对焦。 | -**返回值:** +## VideoStabilizationMode -| 类型 | 说明 | -| ------------------------------------------- | ----------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession实例。 | +枚举,视频防抖模式。 -**示例:** +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -```js -camera.createCaptureSession(context).then((captureSession) => { - console.log('Promise returned with the CaptureSession instance'); -}) -``` +| 名称 | 值 | 说明 | +| --------- | ---- | ------------ | +| OFF | 0 | 关闭视频防抖功能。 | +| LOW | 1 | 使用基础防抖算法。 | +| MIDDLE | 2 | 使用防抖效果一般的防抖算法,防抖效果优于LOW类型。 | +| HIGH | 3 | 使用防抖效果最好的防抖算法,防抖效果优于MIDDLE类型。 | +| AUTO | 4 | 自动进行选择。 | ## CaptureSession -拍照会话类。 +拍照会话类,保存一次相机运行所需要的所有资源[CameraInput](#camerainput)、[CameraOutput](#cameraoutput),并向相机设备申请完成相机功能(录像,拍照)。 ### beginConfig @@ -1173,8 +1048,8 @@ beginConfig\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1182,7 +1057,7 @@ beginConfig\(callback: AsyncCallback\): void ```js captureSession.beginConfig((err) => { if (err) { - console.error('Failed to start the configuration. ${err.message}'); + console.error(`Failed to start the configuration. ${err.message}`); return; } console.log('Callback invoked to indicate the begin config success.'); @@ -1199,8 +1074,8 @@ beginConfig\(\): Promise **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | @@ -1216,14 +1091,14 @@ captureSession.beginConfig().then(() => { commitConfig\(callback: AsyncCallback\): void -提交会话配置,通过注册回调函数获取结果。 +提交配置信息,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1231,7 +1106,7 @@ commitConfig\(callback: AsyncCallback\): void ```js captureSession.commitConfig((err) => { if (err) { - console.error('Failed to commit the configuration. ${err.message}'); + console.error(`Failed to commit the configuration. ${err.message}`); return; } console.log('Callback invoked to indicate the commit config success.'); @@ -1242,14 +1117,14 @@ captureSession.commitConfig((err) => { commitConfig\(\): Promise -提交会话配置,通过Promise获取结果。 +提交配置信息,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1264,14 +1139,14 @@ captureSession.commitConfig().then(() => { addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -在当前会话中,添加一个CameraInput实例,通过注册回调函数获取结果。 +把[CameraInput](#camerainput)加入到会话,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | @@ -1280,7 +1155,7 @@ addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void ```js captureSession.addInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); + console.error(`Failed to add the CameraInput instance. ${err.message}`); return; } console.log('Callback invoked to indicate that the CameraInput instance is added.'); @@ -1291,20 +1166,20 @@ captureSession.addInput(cameraInput, (err) => { addInput\(cameraInput: CameraInput\): Promise -在当前会话中,添加一个CameraInput实例,通过Promise获取结果。 +把[CameraInput](#camerainput)加入到会话,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1315,969 +1190,2262 @@ captureSession.addInput(cameraInput).then(() => { }) ``` -### addOutput +### removeInput -addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -在当前会话中,添加一个PreviewOutput实例,通过注册回调函数获取结果。 +移除[CameraInput](#camerainput),通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(previewOutput, (err) => { +captureSession.removeInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); + console.error(`Failed to remove the CameraInput instance. ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); + console.log('Callback invoked to indicate that the cameraInput instance is removed.'); }); ``` -### addOutput +### removeInput -addOutput\(previewOutput: PreviewOutput\): Promise +removeInput\(cameraInput: CameraInput\): Promise -在当前会话中,添加一个PreviewOutput实例,通过Promise获取结果。 +移除[CameraInput](#camerainput),通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.addOutput(previewOutput).then(() => { - console.log('Promise used to indicate that the PreviewOutput instance is added.'); +captureSession.removeInput(cameraInput).then(() => { + console.log('Promise returned to indicate that the cameraInput instance is removed.'); }) ``` ### addOutput -addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void +addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -在当前会话中,添加一个PhotoOutput实例,通过注册回调函数获取结果。 +把[CameraOutput](#cameraoutput)加入到会话,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要添加的CameraOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(photoOutput, (err) => { +captureSession.addOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); + console.error(`Failed to add output. ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); -}); + console.log('Callback returned with output added.'); +}) ``` ### addOutput -addOutput\(photoOutput: PhotoOutput\): Promise +addOutput\(cameraOutput: CameraOutput\): Promise -在当前会话中,添加一个PhotoOutput实例,通过Promise获取结果。 +把[CameraOutput](#cameraoutput)加入到会话,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要添加的CameraOutput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.addOutput(photoOutput).then(() => { - console.log('Promise used to indicate that the PhotoOutput instance is added.'); +captureSession.addOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput added.'); }) ``` -### addOutput +### removeOutput -addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void +removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -在当前会话中,添加一个VideoOutput实例,通过注册回调函数获取结果。 +从会话中移除[CameraOutput](#cameraoutput),通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要移除的CameraOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(videoOutput, (err) => { +captureSession.removeOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); + console.error(`Failed to remove the CameraOutput instance. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); + console.log('Callback invoked to indicate that the CameraOutput instance is removed.'); }); ``` -### addOutput +### removeOutput -addOutput\(videoOutput: VideoOutput\): Promise +removeOutput(cameraOutput: CameraOutput): Promise -在当前会话中,添加一个VideoOutput实例,通过Promise获取结果。 +从会话中移除[CameraOutput](#cameraoutput),通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要移除的CameraOutput实例。 | + **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + **示例:** ```js -captureSession.addOutput(videoOutput).then(() => { - console.log('Promise used to indicate that the VideoOutput instance is added.'); +captureSession.removeOutput(cameraOutput).then(() => { + console.log('Promise returned to indicate that the CameraOutput instance is removed.'); }) ``` -### removeInput +### start -removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +start\(callback: AsyncCallback\): void -在当前会话中,移除一个CameraInput实例,通过注册回调函数获取结果。 +开始会话工作,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeInput(cameraInput, (err) => { +captureSession.start((err) => { if (err) { - console.error('Failed to remove the CameraInput instance. ${err.message}'); + console.error(`Failed to start the session ${err.message}`); return; } - console.log('Callback invoked to indicate that the cameraInput instance is removed.'); + console.log('Callback invoked to indicate the session start success.'); }); ``` -### removeInput +### start -removeInput\(cameraInput: CameraInput\): Promise +start\(\): Promise -在当前会话中,移除一个CameraInput实例,通过Promise获取结果。 +开始会话工作,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.removeInput(cameraInput).then(() => { - console.log('Promise returned to indicate that the cameraInput instance is removed.'); +captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); }) ``` -### removeOutput +### stop -removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +stop\(callback: AsyncCallback\): void -在当前会话中,移除一个PreviewOutput实例,通过注册回调函数获取结果。 +停止会话工作,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeOutput(previewOutput, (err) => { +captureSession.stop((err) => { if (err) { - console.error('Failed to remove the PreviewOutput instance. ${err.message}'); + console.error(`Failed to stop the session ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is removed.'); + console.log('Callback invoked to indicate the session stop success.'); }); ``` -### removeOutput +### stop -removeOutput(previewOutput: PreviewOutput): Promise +stop(): Promise -在当前会话中,移除一个PreviewOutput实例,通过Promise获取结果。 +停止会话工作,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | - - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -captureSession.removeOutput(previewOutput).then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); +captureSession.stop().then(() => { + console.log('Promise returned to indicate the session stop success.'); }) ``` -### removeOutput +### release -removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void +release\(callback: AsyncCallback\): void -在当前会话中,移除一个PhotoOutput实例,通过注册回调函数获取结果。 +释放会话资源,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要移除的PhotoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeOutput(photoOutput, (err) => { +captureSession.release((err) => { if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); + console.error(`Failed to release the CaptureSession instance ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); + console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); }); ``` -### removeOutput +### release -removeOutput(photoOutput: PhotoOutput): Promise +release(): Promise -在当前会话中,移除一个PhotoOutput实例,通过Promise获取结果。 +释放会话资源,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要移除的PhotoOutput实例。 | - - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -captureSession.removeOutput(photoOutput).then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); +captureSession.release().then(() => { + console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); }) ``` -### removeOutput +### hasFlash -removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void +hasFlash(callback: AsyncCallback): void -在当前会话中,移除一个VideoOutput实例,通过注册回调函数获取结果。 +检测是否有闪光灯,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要移除的VideoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | **示例:** ```js -captureSession.removeOutput(videoOutput, (err) => { +captureSession.hasFlash((err, status) => { if (err) { - console.error('Failed to remove the VideoOutput instance. ${err.message}'); + console.error(`Failed to check whether the device has flash light. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is removed.'); -}); + console.log(`Callback returned with flash light support status: ${status}`); +}) ``` -### removeOutput +### hasFlash -removeOutput(videoOutput: VideoOutput): Promise +hasFlash(): Promise -在当前会话中,移除一个VideoOutput实例,通过Promise获取结果。 +检测是否有闪光灯,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要移除的VideoOutput实例。 | - - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - +| 类型 | 说明 | +| ----------------- | ----------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | **示例:** ```js -captureSession.removeOutput(videoOutput).then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is removed.'); +captureSession.hasFlash().then((status) => { + console.log(`Promise returned with the flash light support status: ${status}`); }) ``` -### start +### isFlashModeSupported -start\(callback: AsyncCallback\): void +isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void -启动拍照会话,通过注册回调函数获取结果。 +检测闪光灯模式是否支持,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | --------------------------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | **示例:** ```js -captureSession.start((err) => { +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { - console.error('Failed to start the session ${err.message}'); + console.error(`Failed to check whether the flash mode is supported. ${err.message}`); return; } - console.log('Callback invoked to indicate the session start success.'); -}); + console.log(`Callback returned with the flash mode support status: ${status}`); +}) ``` -### start +### isFlashModeSupported -start\(\): Promise +isFlashModeSupported(flashMode: FlashMode): Promise -启动拍照会话,通过Promise获取结果。 +检测闪光灯模式是否支持,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | + **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ----------------- | ---------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | **示例:** ```js -captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { + console.log(`Promise returned with flash mode support status.${status}`); }) ``` -### stop +### setFlashMode -stop\(callback: AsyncCallback\): void +setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void + +设置闪光灯模式,通过注册回调函数获取结果。 + +进行设置之前,需要先检查: -停止拍照会话,通过注册回调函数获取结果。 +1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 +2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | --------------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.stop((err) => { +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { - console.error('Failed to stop the session ${err.message}'); + console.error(`Failed to set the flash mode ${err.message}`); return; } - console.log('Callback invoked to indicate the session stop success.'); -}); + console.log('Callback returned with the successful execution of setFlashMode.'); +}) ``` -### stop +### setFlashMode -stop(): Promise +setFlashMode(flashMode: FlashMode): Promise + +设置闪光灯模式,通过Promise获取结果。 + +进行设置之前,需要先检查: -停止拍照会话,通过Promise获取结果。 +1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 +2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | + **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.stop().then(() => { - console.log('Promise returned to indicate the session stop success.'); +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` -### release +### getFlashMode -release\(callback: AsyncCallback\): void +getFlashMode(callback: AsyncCallback): void -释放CaptureSession实例,通过注册回调函数获取结果。 +获取当前设备的闪光灯模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | --------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | **示例:** ```js -captureSession.release((err) => { +captureSession.getFlashMode((err, flashMode) => { if (err) { - console.error('Failed to release the CaptureSession instance ${err.message}'); + console.error(`Failed to get the flash mode ${err.message}`); return; } - console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); -}); + console.log(`Callback returned with current flash mode: ${flashMode}`); +}) ``` -### release +### getFlashMode -release(): Promise +getFlashMode(): Promise -释放CaptureSession实例,通过Promise获取结果。 +获取当前设备的闪光灯模式,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| --------------------------------- | --------------------------------- | +| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | **示例:** ```js -captureSession.release().then(() => { - console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); +captureSession.getFlashMode().then((flashMode) => { + console.log(`Promise returned with current flash mode : ${flashMode}`); }) ``` -### on('error') +### isExposureModeSupported -on(type: 'error', callback: ErrorCallback): void +isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; -监听拍照会话的错误事件,通过注册回调函数获取结果。 +检测曝光模式是否支持,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即拍照会话错误事件。 | -| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取是否支持曝光模式。 | **示例:** ```js -captureSession.on('error', (captureSessionError) => { - console.log('Capture session error code: ' + captureSessionError.code); +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log(`Failed to check exposure mode supported ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of isExposureModeSupported'); }) ``` -## CaptureSessionErrorCode +### isExposureModeSupported -枚举,拍照会话的错误码。 +isExposureModeSupported(aeMode: ExposureMode): Promise + +检测曝光模式是否支持,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +**参数:** -## CaptureSessionError +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | -拍照会话错误对象。 +**返回值:** -**系统能力:** SystemCapability.Multimedia.Camera.Core +| 名称 | 说明 | +| ----------------- |--------------------------------- | +| Promise | 使用Promise的方式获取支持的曝光模式。 | -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | CaptureSession中的错误码。 | +**示例:** -## camera.createPreviewOutput +```js +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log(`Promise returned with exposure mode supported : ${isSupported}`); +}) +``` + +### getExposureMode -createPreviewOutput(surfaceId: string, callback: AsyncCallback): void +getExposureMode(callback: AsyncCallback): void -获取PreviewOutput实例,通过注册回调函数获取结果。 +获取当前曝光模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------------------------------- | ---- | ------------------------------------- | -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ---------------------------------------- | +| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | 是 | 回调函数,用于获取当前曝光模式。 | **示例:** ```js -camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { +captureSession.getExposureMode((err, exposureMode) => { if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); - return; + console.log(`Failed to get the exposure mode ${err.message}`); + return ; } - console.log('Callback returned with previewOutput instance'); -}); + console.log(`Callback returned with current exposure mode: ${exposureMode}`); +}) +``` + +### getExposureMode + +getExposureMode(): Promise + +获取当前曝光模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| --------------------------------------- |------------------------------- | +| Promise<[ExposureMode](#exposuremode)\> | 使用Promise的方式获取当前曝光模式。 | + +**示例:** + +```js +captureSession.getExposureMode().then((exposureMode) => { + console.log(`Promise returned with current exposure mode : ${exposureMode}`); +}) ``` -## camera.createPreviewOutput +### setExposureMode -createPreviewOutput(surfaceId: string): Promise\ +setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void -获取PreviewOutput实例,通过Promise获取结果。 +设置曝光模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ---------------------------------- | -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取设置结果。 | + +**示例:** + +```js +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log(`Failed to set the exposure mode ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of setExposureMode'); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode): Promise + +设置曝光模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ----------------------------------------- | --------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取结果。 | +| 名称 | 说明 | +| ----------------- |---------------------------- | +| Promise | 使用Promise的方式获取设置结果。 | **示例:** ```js -camera.createPreviewOutput("surfaceId").then((previewOutput) => { - console.log('Promise returned with the PreviewOutput instance'); +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { + console.log('Promise returned with the successful execution of setExposureMode.'); }) ``` -## PreviewOutput +### getMeteringPoint -预览输出类。 +getMeteringPoint(callback: AsyncCallback): void -### release +查询曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放) -release(callback: AsyncCallback): void +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ------------------------ | +| callback | AsyncCallback<[Point](#point)\>| 是 | 回调函数,用于获取当前曝光点。 | + +**示例:** + +```js +captureSession.getMeteringPoint((err, exposurePoint) => { + if (err) { + console.log(`Failed to get the current exposure point ${err.message}`); + return ; + } + console.log(`Callback returned with current exposure point: ${exposurePoint}`); +}) +``` + +### getMeteringPoint + +getMeteringPoint(): Promise + +查询曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ------------------------- |----------------------------- | +| Promise<[Point](#point)\> | 使用Promise的方式获取当前曝光点。 | + +**示例:** + +```js +captureSession.getMeteringPoint().then((exposurePoint) => { + console.log(`Promise returned with current exposure point : ${exposurePoint}`); +}) +``` + +### setMeteringPoint -释放PreviewOutput实例,通过注册回调函数获取结果。 +setMeteringPoint(point: Point, callback: AsyncCallback): void + +设置曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | 是 | 曝光点。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -previewOutput.release((err) => { +const Point1 = {x: 1, y: 1}; + +captureSession.setMeteringPoint(Point1,(err) => { if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); - return; + console.log(`Failed to set the exposure point ${err.message}`); + return ; } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); + console.log('Callback returned with the successful execution of setMeteringPoint'); +}) ``` -### release +### setMeteringPoint -release(): Promise +setMeteringPoint(point: Point): Promise -释放PreviewOutput实例,通过Promise获取结果。 +设置曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | 是 | 曝光点。 | + **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 名称 | 说明 | +| ----------------- |------------------------ | +| Promise | 使用Promise的方式返回结果。 | + +**示例:** + +```js +const Point2 = {x: 2, y: 2}; + +captureSession.setMeteringPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setMeteringPoint'); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(callback: AsyncCallback\>): void +查询曝光补偿范围,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| callback | AsyncCallback\> | 是 | 回调函数,用于获取补偿范围的数组。 | **示例:** ```js -previewOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +captureSession.getExposureBiasRange((err, biasRangeArray) => { + if (err) { + console.log(`Failed to get the array of compenstation range ${err.message}`); + return ; + } + console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); }) ``` -### on('frameStart') +### getExposureBiasRange -on(type: 'frameStart', callback: AsyncCallback): void +getExposureBiasRange(): Promise\> -监听预览帧启动,通过注册回调函数获取结果。 +查询曝光补偿范围,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ----------------- |-------------------------------------- | +| Promise\> | 使用Promise的方式获取曝光补偿范围。 | + +**示例:** + +```js +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log(`Promise returned with exposure mode supported : ${isSupported}`); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number, callback: AsyncCallback): void + +设置曝光补偿,通过注册回调函数获取结果。 + +进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ------------------- | +| exposureBias | number | 是 | 曝光补偿。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -previewOutput.on('frameStart', () => { - console.log('Preview frame started'); +captureSession.setExposureBias(-4,(err) => { + if (err) { + console.log(`Failed to set the exposure bias ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of setExposureBias'); }) ``` -### on('frameEnd') +### setExposureBias -on(type: 'frameEnd', callback: AsyncCallback): void +setExposureBias(exposureBias: number): Promise -监听预览帧结束,通过注册回调函数获取结果。 +设置曝光补偿,通过Promise获取结果。 + +进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------- | --------- | ---- | --------- | +| exposureBias | number | 是 | 曝光补偿。 | + +**返回值:** + +| 名称 | 说明 | +| ----------------- |------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -previewOutput.on('frameEnd', () => { - console.log('Preview frame ended'); +captureSession.setExposureBias(-4).then(() => { + console.log('Promise returned with the successful execution of setExposureBias.'); }) ``` -### on('error') +### getExposureValue -on(type: 'error', callback: ErrorCallback): void +getExposureValue(callback: AsyncCallback): void -监听预览输出的错误事件,通过注册回调函数获取结果。 +查询当前曝光值,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即预览输出错误事件。 | -| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------| ---- | --------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取曝光值。 | **示例:** ```js -previewOutput.on('error', (previewOutputError) => { - console.log('Preview output error code: ' + previewOutputError.code); +captureSession.getExposureValue((err, exposureValue) => { + if (err) { + console.log(`Failed to get the exposure value ${err.message}`); + return ; + } + console.log(`Callback returned with the exposure value: ${exposureValue}`); }) ``` -## PreviewOutputErrorCode +### getExposureValue + +getExposureValue(): Promise -枚举,预览输出的错误码。 +查询当前曝光值,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +**返回值:** + +| 名称 | 说明 | +| ----------------- |-------------------------- | +| Promise | 使用Promise的方式获取曝光值。 | + +**示例:** -## PreviewOutputError +```js +captureSession.getExposureValue().then((exposureValue) => { + console.log(`Promise returned with exposure value: ${exposureValude}`); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void -预览输出错误对象。 +检测对焦模式是否支持,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------------- | ---------------------- | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOutput中的错误码。 | +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | + +**示例:** + +```js +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; + } + console.log(`Callback returned with the focus mode support status: ${status}`); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode): Promise + +检测对焦模式是否支持,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | --------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | + +**示例:** + +```js +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { + console.log(`Promise returned with focus mode support status ${status}.`); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode, callback: AsyncCallback): void + +设置对焦模式,通过注册回调函数获取结果。 + +进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { + if (err) { + console.error(`Failed to set the focus mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setFocusMode.'); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode): Promise + +设置对焦模式,通过Promise获取结果。 + +进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFocusMode.'); +}) +``` + +### getFocusMode + +getFocusMode(callback: AsyncCallback): void + +获取当前的对焦模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | + +**示例:** + +```js +captureSession.getFocusMode((err, afMode) => { + if (err) { + console.error(`Failed to get the focus mode ${err.message}`); + return; + } + console.log(`Callback returned with current focus mode: ${afMode}`); +}) +``` + +### getFocusMode + +getFocusMode(): Promise + +获取当前的对焦模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise | 使用Promise的方式获取当前的焦距模式。 | + +**示例:** + +```js +captureSession.getFocusMode().then((afMode) => { + console.log(`Promise returned with current focus mode : ${afMode}`); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point, callback: AsyncCallback): void + +设置焦点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#point) | 是 | 焦点。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +const Point1 = {x: 1, y: 1}; + +captureSession.setFocusPoint(Point1, (err) => { + if (err) { + console.error(`Failed to set the focus point ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setFocusPoint.'); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point): Promise + +设置焦点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#point) | 是 | 焦点。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +const Point2 = {x: 2, y: 2}; + +captureSession.setFocusPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setFocusPoint.'); +}) +``` + +### getFocusPoint + +getFocusPoint(callback: AsyncCallback): void + +查询焦点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ----------------------- | +| callback | AsyncCallback<[Point](#point)\> | 是 | 回调函数,用于获取当前焦点。 | + +**示例:** + +```js +captureSession.getFocusPoint((err, point) => { + if (err) { + console.error(`Failed to get the current focus point ${err.message}`); + return; + } + console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocusPoint + +getFocusPoint(): Promise + +查询焦点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| --------------- | --------------------------- | +| Promise | 使用Promise的方式获取当前焦点。 | + +**示例:** + +```js +captureSession.getFocusPoint().then((point) => { + console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocalLength + +getFocalLength(callback: AsyncCallback): void + +查询焦距值,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取当前焦距。 | + +**示例:** + +```js +captureSession.getFocalLength((err, focalLength) => { + if (err) { + console.error(`Failed to get the current focal length ${err.message}`); + return; + } + console.log(`Callback returned with the current focal length: ${focalLength}`); +}) +``` + +### getFocalLength + +getFocalLength(): Promise + +查询焦距值,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------- | +| Promise | 使用Promise的方式获取焦距。 | + +**示例:** + +```js +captureSession.getFocalLength().then((focalLength) => { + console.log(`Promise returned with the current focal length: ${focalLength}`); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(callback: AsyncCallback\>\): void + +获取支持的变焦范围,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------ | ---- | ------------------- | +| callback | AsyncCallback\> | 是 | 回调函数,用于获取可变焦距比范围,返回的数组包括其最小值和最大值。 | + +**示例:** + +```js +captureSession.getZoomRatioRange((err, zoomRatioRange) => { + if (err) { + console.error(`Failed to get the zoom ratio range. ${err.message}`); + return; + } + console.log(`Callback returned with zoom ratio range: ${zoomRatioRange.length}`); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(\): Promise\> + +获取支持的变焦范围,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | --------------------------- | +| Promise\> | 使用Promise的方式获取当前的可变焦距比范围,返回的数组包括其最小值和最大值。 | + +**示例:** + +```js +captureSession.getZoomRatioRange().then((zoomRatioRange) => { + console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number, callback: AsyncCallback): void + +设置变焦比,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | -------------------- | ---- | ------------------- | +| zoomRatio | number | 是 | 可变焦距比。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +captureSession.setZoomRatio(1, (err) => { + if (err) { + console.error(`Failed to set the zoom ratio value ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setZoomRatio.'); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number): Promise + +设置变焦比,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------- | +| zoomRatio | number | 是 | 可变焦距比。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +captureSession.setZoomRatio(1).then(() => { + console.log('Promise returned with the successful execution of setZoomRatio.'); +}) +``` + +### getZoomRatio + +getZoomRatio(callback: AsyncCallback): void + +获取当前的变焦比,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +captureSession.getZoomRatio((err, zoomRatio) => { + if (err) { + console.error(`Failed to get the zoom ratio ${err.message}`); + return; + } + console.log(`Callback returned with current zoom ratio: ${zoomRatio}`); +}) +``` + +### getZoomRatio + +getZoomRatio(): Promise + +获取当前的变焦比,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +captureSession.getZoomRatio().then((zoomRatio) => { + console.log(`Promise returned with current zoom ratio : ${zoomRatio}`); +}) +``` + +### isVideoStabilizationModeSupported + +isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void + +查询是否支持指定的视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ------------------------------ | +| vsMode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 视频防抖模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回视频防抖模式是否支持。 | + +**示例:** + +```js +captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => { + if (err) { + console.error(`Failed to check whether video stabilization mode supported. ${err.message}`); + return; + } + console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported: ${status}`); +}) +``` + +### isVideoStabilizationModeSupported + +isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise + +查询是否支持指定的视频防抖模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------- | --------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回视频防抖模式是否支持。 | + +**示例:** + +```js +captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => { + console.log(`Promise returned with video stabilization mode supported: ${isSupported}`); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(callback: AsyncCallback): void + +查询当前正在使用的视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback | 是 | 回调函数,返回视频防抖是否正在使用。 | + +**示例:** + +```js +captureSession.getActiveVideoStabilizationMode((err, vsMode) => { + if (err) { + console.error(`Failed to get active video stabilization mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(): Promise + +查询当前正在使用的视频防抖模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------------------------- | ------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回视频防抖当前是否正在使用。 | + +**示例:** + +```js +captureSession.getActiveVideoStabilizationMode().then((vsMode) => { + console.log(`Promise returned with the current video stabilization mode: ${vsMode}`); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void + +设置视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 需要设置的视频防抖模式。 | +| callback | AsyncCallback | 是 | 回调函数。 | + +**示例:** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { + if (err) { + console.error(`Failed to set the video stabilization mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode): Promise + +设置视频防抖,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 需要设置的视频防抖模式。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回设置的视频防抖模式的结果。 | + +**示例:** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { + console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### on('focusStateChange') + +on(type: 'focusStateChange', callback: AsyncCallback): void + +监听焦距的状态变化,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | +| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | + +**示例:** + +```js +captureSession.on('focusStateChange', (focusState) => { + console.log(`Focus state : ${focusState}`); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +监听拍照会话的错误事件,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | +| type | string | 是 | 监听事件,固定为'error',即拍照会话错误事件。 | +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | 是 | 回调函数,用于获取错误信息。 | + +**示例:** + +```js +captureSession.on('error', (captureSessionError) => { + console.log(`Capture session error code: ${captureSessionError.code}`); +}) +``` + +## CaptureSessionErrorCode + +枚举,会话错误类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 | +| ERROR_TIMEOUT | 1 | 超时。 | + +## CaptureSessionError + +会话错误码。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | CaptureSession中的错误码。 | + +## CameraOutput + +会话中[CaptureSession](#capturesession)使用的输出信息,output的基类。 + +### release + +release(callback: AsyncCallback): void + +释放输出资源,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraOutput.release((err) => { + if (err) { + console.error(`Failed to release the PreviewOutput instance ${err.message}`); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +释放输出资源,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +}) +``` + +## PreviewOutput + +预览输出类。继承[CameraOutput](#cameraoutput) + +### start + +start(callback: AsyncCallback): void + +开始输出预览流,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.start((err) => { + if (err) { + console.error(`Failed to start the previewOutput. ${err.message}`); + return; + } + console.log('Callback returned with previewOutput started.'); +}) +``` + +### start + +start(): Promise + +开始输出预览流,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.start().then(() => { + console.log('Promise returned with previewOutput started.'); +}) +``` + +### stop + +stop(callback: AsyncCallback): void + +停止输出预览流,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.stop((err) => { + if (err) { + console.error(`Failed to stop the previewOutput. ${err.message}`); + return; + } + console.log('Callback returned with previewOutput stopped.'); +}) +``` + +### stop + +stop(): Promise + +停止输出预览流,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.stop().then(() => { + console.log('Callback returned with previewOutput stopped.'); +}) +``` + +### on('frameStart') + +on(type: 'frameStart', callback: AsyncCallback): void + +监听预览帧启动,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.on('frameStart', () => { + console.log('Preview frame started'); +}) +``` + +### on('frameEnd') + +on(type: 'frameEnd', callback: AsyncCallback): void + +监听预览帧结束,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.on('frameEnd', () => { + console.log('Preview frame ended'); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +监听预览输出的错误事件,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'error',即预览输出错误事件。| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | 是 | 回调函数,用于获取错误信息。 | + +**示例:** + +```js +previewOutput.on('error', (previewOutputError) => { + console.log(`Preview output error code: ${previewOutputError.code}`); +}) +``` + +## PreviewOutputErrorCode + +枚举,预览输出错误类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | + +## PreviewOutputError + +预览输出错误码。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------------------- | ---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOutput中的错误码。 | + +## ImageRotation + +枚举,图片旋转角度。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ------------ | ---- | ------------- | +| ROTATION_0 | 0 | 图片旋转0度。 | +| ROTATION_90 | 90 | 图片旋转90度。 | +| ROTATION_180 | 180 | 图片旋转180度。 | +| ROTATION_270 | 270 | 图片旋转270度。 | + +## Location + +图片地理位置信息。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 必填 |说明 | +| ------------ | ------ | --- |------------ | +| latitude | number | 是 |纬度(度)。 | +| longitude | number | 是 |经度(度)。 | +| altitude | number | 是 |海拔(米)。 | + +## QualityLevel + +枚举,图片质量。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| -------------------- | ---- | ------------ | +| QUALITY_LEVEL_HIGH | 0 | 图片质量高。 | +| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。 | +| QUALITY_LEVEL_LOW | 2 | 图片质量差。 | + + +## PhotoCaptureSetting + +拍摄照片的设置。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 必填 | 默认值 | 说明 | +| -------- | ------------------------------- | ---- | ----------------- | -----------------| +| quality | [QualityLevel](#qualitylevel) | 否 | QUALITY_LEVEL_HIGH| 图片质量。 | +| rotation | [ImageRotation](#imagerotation) | 否 | ROTATION_0 | 图片旋转角度。 | +| location | [Location](#location) | 否 | (0,0,0) | 图片地理位置信息。 | +| mirror | boolean | 否 | false |镜像使能开关(默认关)。 | + +## PhotoOutput + +拍照会话中使用的输出信息。 + +### capture + +capture(callback: AsyncCallback): void + +以默认设置触发一次拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +photoOutput.capture((err) => { + if (err) { + console.error(`Failed to capture the photo ${err.message}`); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` + +### capture + +capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void + +以指定参数触发一次拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | -------------------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} +photoOutput.capture(settings, (err) => { + if (err) { + console.error(`Failed to capture the photo ${err.message}`); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` + +### capture + +capture(setting?: PhotoCaptureSetting): Promise + +以指定参数触发一次拍照,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------- | ---- | -------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + + +**示例:** + +```js +photoOutput.capture().then(() => { + console.log('Promise returned to indicate that photo capture request success.'); +}) +``` + +### isMirrorSupported + +isMirrorSupported(callback: AsyncCallback): void + +查询是否支持镜像拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回是否支持镜像拍照。 | + +**示例:** + +```js +captureSession.isMirrorSupported((err, isSupported) => { + if (err) { + console.error(`Failed to check mirror is supported ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of isMirrorSupported.'); +}) +``` + +### isMirrorSupported + +isMirrorSupported(): Promise + +查询是否支持镜像拍照,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回是否支持自拍结果。 | + +**示例:** + +```js +captureSession.isMirrorSupported().then((isSupported) => { + console.log(`Promise returned with mirror supported: ${isSupported}`); +}) +``` + +### on('captureStart') + +on(type: 'captureStart', callback: AsyncCallback): void + +监听拍照开始,通过注册回调函数获取Capture ID。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | +| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | + +**示例:** + +```js +photoOutput.on('captureStart', (err, captureId) => { + console.log(`photo capture stated, captureId : ${captureId}`); +}) +``` + +### on('frameShutter') + +on(type: 'frameShutter', callback: AsyncCallback): void + +监听拍照帧输出捕获,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | --- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 | + +**示例:** -## camera.createPhotoOutput +```js +photoOutput.on('frameShutter', (err, frameShutterInfo) => { + console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`); + console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`); +}) +``` -createPhotoOutput(surfaceId: string, callback: AsyncCallback): void +### on('captureEnd') + +on(type: 'captureEnd', callback: AsyncCallback): void -获取PhotoOutput实例,通过注册回调函数获取结果。 +监听拍照结束,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的Surface ID。 | -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 | **示例:** ```js -camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { - if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with the PhotoOutput instance.'); -}); +photoOutput.on('captureEnd', (err, captureEndInfo) => { + console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`); + console.log(`frameCount : ${captureEndInfo.frameCount}`); +}) ``` -## camera.createPhotoOutput +### on('error') -createPhotoOutput(surfaceId: string): Promise +on(type: 'error', callback: ErrorCallback): void -获取PhotoOutput实例,通过Promise获取结果。 +监听拍照输出发生错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的Surface ID。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | -------------------------------------- | -| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即拍照错误事件。 | +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -camera.createPhotoOutput("surfaceId").then((photoOutput) => { - console.log('Promise returned with PhotoOutput instance'); +photoOutput.on('error', (err, photoOutputError) => { + console.log(`Photo output error code: ${photoOutputError.code}`); }) ``` -## ImageRotation - -枚举,图片旋转角度。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -| 名称 | 值 | 说明 | -| ------------ | ---- | --------------- | -| ROTATION_0 | 0 | 图片旋转0度。 | -| ROTATION_90 | 90 | 图片旋转90度。 | -| ROTATION_180 | 180 | 图片旋转180度。 | -| ROTATION_270 | 270 | 图片旋转270度。 | -## QualityLevel +## FrameShutterInfo -枚举,图片质量。 +拍照帧输出信息。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| -------------------- | ---- | -------------- | -| QUALITY_LEVEL_HIGH | 0 | 图片质量高。 | -| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。 | -| QUALITY_LEVEL_LOW | 2 | 图片质量差。 | - +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------- | +| captureId | number | 是 | 拍照的ID。 | +| timestamp | number | 是 | 快门时间戳。 | -## PhotoCaptureSetting +## CaptureEndInfo -拍摄照片的设置。 +拍照停止信息。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------- | ---- | -------------- | -| quality | [QualityLevel](#qualitylevel) | 否 | 图片质量。 | -| rotation | [ImageRotation](#imagerotation) | 否 | 图片旋转角度。 | +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ---------| +| captureId | number | 是 | 拍照的ID。 | +| frameCount | number | 是 | 帧数。 | +## PhotoOutputErrorCode -## PhotoOutput +枚举,拍照输出错误类型。 -照片输出类。 +**系统能力:** SystemCapability.Multimedia.Camera.Core -### capture +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | --------------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 1 | 资源不足。 | +| ERROR_TIMEOUT | 2 | 超时。 | -capture(callback: AsyncCallback): void +## PhotoOutputError -拍照,通过注册回调函数获取结果。 +拍照输出错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | PhotoOutput中的错误码。 | -**示例:** +## VideoOutput -```js -photoOutput.capture((err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` +录像会话中使用的输出信息。 -### capture +### start -capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void +start(callback: AsyncCallback): void -根据拍照设置拍照,通过注册回调函数获取结果。 +启动录制,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ------------------------ | -| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 -} -photoOutput.capture(settings, (err) => { +videoOutput.start((err) => { if (err) { - console.error('Failed to capture the photo ${err.message}'); + console.error(`Failed to start the video output ${err.message}`); return; } - console.log('Callback invoked to indicate the photo capture request success.'); + console.log('Callback invoked to indicate the video output start success.'); }); ``` -### capture +### start -capture(setting?: PhotoCaptureSetting): Promise +start(): Promise -根据拍照设置拍照,通过Promise获取结果。 +启动录制,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------- | ------------------------------------------- | ---- | ---------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -photoOutput.capture().then(() => { - console.log('Promise returned to indicate that photo capture request success.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that start method execution success.'); }) ``` -### release +### stop -release(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -释放PhotoOutput实例,通过注册回调函数获取结果。 +结束录制,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2290,465 +3458,465 @@ release(callback: AsyncCallback): void **示例:** ```js -photoOutput.release((err) => { +videoOutput.stop((err) => { if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); + console.error(`Failed to stop the video output ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); + console.log('Callback invoked to indicate the video output stop success.'); }); ``` -### release +### stop -release(): Promise +stop(): Promise -释放PhotoOutput实例,通过Promise获取结果。 +结束录制,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -photoOutput.release().then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); +videoOutput.stop().then(() => { + console.log('Promise returned to indicate that stop method execution success.'); }) -``` +``` -### on('captureStart') +### on('frameStart') -on(type: 'captureStart', callback: AsyncCallback): void +on(type: 'frameStart', callback: AsyncCallback): void -监听拍照启动,通过注册回调函数获取Capture ID。 +监听录像开始,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :--- | :----------------------------------------------- | -| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | -| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ----------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -photoOutput.on('captureStart', (err, captureId) => { - console.log('photo capture stated, captureId : ' + captureId); +videoOutput.on('frameStart', () => { + console.log('Video frame started'); }) ``` -### on('frameShutter') +### on('frameEnd') -on(type: 'frameShutter', callback: AsyncCallback): void +on(type: 'frameEnd', callback: AsyncCallback): void -监听快门,通过注册回调函数获取结果。 +监听录像结束,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件 。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -photoOutput.on('frameShutter', (err, frameShutterInfo) => { - console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); - console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +videoOutput.on('frameEnd', () => { + console.log('Video frame ended'); }) ``` -### on('captureEnd') +### on('error') -on(type: 'captureEnd', callback: AsyncCallback): void +on(type: 'error', callback: ErrorCallback): void -监听拍照停止,通过注册回调函数获取结果。 +监听录像输出发生错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------------------------------------ | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | -| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | -------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即视频输出错误事件。 | +| callback | Callback<[VideoOutputError](#videooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.log('photo capture end, captureId : ' + captureEndInfo.captureId); - console.log('frameCount : ' + captureEndInfo.frameCount); +videoOutput.on('error', (VideoOutputError) => { + console.log(`Video output error code: ${VideoOutputError.code}`); }) ``` -### on('error') - -on(type: 'error', callback: ErrorCallback): void +## VideoOutputErrorCode -监听拍照的错误事件,通过注册回调函数获取结果。 +枚举,录像输出错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :---------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即拍照错误事件。 | -| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | - -**示例:** - -```js -photoOutput.on('error', (err, photoOutputError) => { - console.log('Photo output error code: ' + photoOutputError.code); -}) -``` +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------ | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。| -## FrameShutterInfo +## VideoOutputError -快门事件信息。 +录像输出错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ----------------------------- | -| captureId | number | 是 | CaptureId,本次拍摄动作的ID。 | -| timestamp | number | 是 | 时间戳。 | +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | VideoOutput中的错误码。 | -## CaptureEndInfo +## MetadataObjectType -拍照停止信息。 +枚举,metadata流。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | ----------------------------- | -| captureId | number | 是 | CaptureId,本次拍摄动作的ID。 | -| frameCount | number | 是 | 帧计数。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ----------------- | +| FACE_DETECTION | 0 | metadata对象类型。 | -## PhotoOutputErrorCode +## Rect -枚举,拍照输出的错误码。 +矩形定义。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | - -## PhotoOutputError +| 名称 | 类型 | 说明 | +| -------- | ------ | -------------------- | +| topLeftX | number | 矩形区域左上角x坐标。 | +| topLeftY | number | 矩形区域左上角y坐标。 | +| width | number | 矩形宽。 | +| height | number | 矩形高。 | -拍照输出错误对象。 +## MetadataObject -**系统能力:** SystemCapability.Multimedia.Camera.Core - -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | PhotoOutput中的错误码。 | +相机元能力信息,[CameraInput](#camerainput)相机信息中的数据来源。 -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string, callback: AsyncCallback): void +getType(callback: AsyncCallback): void -获取VideoOutput实例,通过注册回调函数获取结果。 +查询metadata对象类型,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | --- | -------------------- | +| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | 是 | 回调函数,用于获取结果。 | **示例:** ```js -camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { +metadataObject.getType((err, metadataObjectType) => { if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); + console.error(`Failed to get type. ${err.message}`); return; } - console.log('Callback returned with the VideoOutput instance'); -}); + console.log('Callback returned with an array of metadataObjectType.'); +}) ``` -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string): Promise +getType(): Promise -获取VideoOutput实例,通过Promise获取结果。 +查询metadata对象类型,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | - **返回值:** -| 类型 | 说明 | -| ------------------------------------- | -------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | 使用Promise的方式获取VideoOutput实例。 | +| 类型 | 说明 | +| --------------------------------------------------- | --------------------------- | +| Promise<[MetadataObjectType](#metadataobjecttype)\> | 使用Promise的方式获取结果。 | **示例:** ```js -camera.createVideoOutput("surfaceId" -).then((videoOutput) => { - console.log('Promise returned with the VideoOutput instance'); +metadataObject.getType().then((metadataObjectType) => { + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -## VideoOutput - -视频输出类。 - -### start +### getTimestamp -start(callback: AsyncCallback): void +getTimestamp(callback: AsyncCallback): void -开始拍摄视频,通过注册回调函数获取结果。 +查询metadata时间戳,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.start((err) => { +metadataObject.getTimestamp((err) => { if (err) { - console.error('Failed to start the video output ${err.message}'); + console.error(`Failed to get timestamp. ${err.message}`); return; } - console.log('Callback invoked to indicate the video output start success.'); -}); + console.log('Callback returned with timestamp getted.'); +}) ``` -### start +### getTimestamp -start(): Promise +getTimestamp(): Promise -开始拍摄视频,通过Promise获取结果。 +查询metadata时间戳,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that start method execution success.'); +metadataObject.getTimestamp().then(() => { + console.log('Callback returned with timestamp getted.'); }) ``` -### stop +### getBoundingBox -stop(callback: AsyncCallback): void +getBoundingBox(callback: AsyncCallback): void -停止拍摄视频,通过注册回调函数获取结果。 +查询metadata的边界框,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.stop((err) => { +metadataObject.getBoundingBox((err, rect) => { if (err) { - console.error('Failed to stop the video output ${err.message}'); + console.error(`Failed to get boundingBox. ${err.message}`); return; } - console.log('Callback invoked to indicate the video output stop success.'); -}); + console.log('Callback returned with boundingBox getted.'); +}) ``` -### stop +### getBoundingBox -stop(): Promise +getBoundingBox(): Promise -停止拍摄视频,通过Promise获取结果。 +查询metadata的边界框,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ---------------------- | --------------------------- | +| Promise<[Rect](#rect)\> | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that stop method execution success.'); +metadataObject.getBoundingBox().then((rect) => { + console.log('Callback returned with boundingBox getted.'); }) ``` -### release +## MetadataFaceObject -release(callback: AsyncCallback): void +metadata的人脸对象。继承[MetadataObject](#metadataobject) + +## MetadataOutput + +metadata流。继承[CameraOutput](#cameraoutput) + +### start + +start(callback: AsyncCallback): void -释放VideoOutput实例,通过注册回调函数获取结果。 +开始输出metadata,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.release((err) => { +metadataOutput.start((err) => { if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); + console.error(`Failed to start metadataOutput. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); + console.log('Callback returned with metadataOutput started.'); +}) ``` -### release +### start -release(): Promise +start(): Promise -释放VideoOutput实例,通过Promise获取结果。 +开始输出metadata,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - +| 类型 | 说明 | +| ---------------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.release().then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); +metadataOutput.start().then(() => { + console.log('Callback returned with metadataOutput started.'); }) ``` -### on('frameStart') +### stop -on(type: 'frameStart', callback: AsyncCallback): void +stop(callback: AsyncCallback): void -监听视频帧开启,通过注册回调函数获取结果。 +停止输出metadata,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.on('frameStart', () => { - console.log('Video frame started'); +metadataOutput.stop((err) => { + if (err) { + console.error(`Failed to stop the metadataOutput. ${err.message}`); + return; + } + console.log('Callback returned with metadataOutput stopped.'); }) ``` -### on('frameEnd') +### stop -on(type: 'frameEnd', callback: AsyncCallback): void +stop(): Promise + +停止输出metadata,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +metadataOutput.stop().then(() => { + console.log('Callback returned with metadataOutput stopped.'); +}) +``` + +### on('metadataObjectsAvailable') -监听视频帧结束,通过注册回调函数获取结果。 +on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void + +监听检测到的metadata对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'metadataObjectsAvailable',即metadata对象。 | +| callback | Callback\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -videoOutput.on('frameEnd', () => { - console.log('Video frame ended'); +metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { + console.log(`metadata output error code: ${metadataObject.code}`); }) ``` ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(type: 'error', callback: ErrorCallback): void -监听视频输出的错误事件,通过注册回调函数获取结果。 +监听metadata流的错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即视频输出错误事件。 | -| callback | Callback<[VideoOutputError](#videooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即metadata流的错误。 | +| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -videoOutput.on('error', (VideoOutputError) => { - console.log('Video output error code: ' + VideoOutputError.code); +metadataOutput.on('error', (metadataOutputError) => { + console.log(`Metadata output error code: ${metadataOutputError.code}`); }) ``` -## VideoOutputErrorCode +## MetadataOutputErrorCode -枚举,视频输出的错误码。 +枚举,metadata输出错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +| 名称 | 值 | 说明 | +| ------------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 | -## VideoOutputError +## MetadataOutputError -视频输出错误对象。 +metadata输出错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 类型 | 说明 | | ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | VideoOutput中的错误码。 | \ No newline at end of file +| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | MetadataOutput中的错误码。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md index f4529508bb648f132586a2b3988fb8d9eda51bbb..7f03c0e62f5e943c3803ebb3327489cdb3030184 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -227,7 +227,7 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\ ```js //公共事件相关信息 -var options = { +let options = { code: 0, //公共事件的初始代码 data: "initial data",//公共事件的初始数据 isOrdered: true //有序公共事件 @@ -279,7 +279,7 @@ function PublishAsUserCallBack(err) { } //指定发送的用户 -var userId = 100; +let userId = 100; //发布公共事件 CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); @@ -311,7 +311,7 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca ```js //公共事件相关信息 -var options = { +let options = { code: 0, //公共事件的初始代码 data: "initial data",//公共事件的初始数据 } @@ -326,7 +326,7 @@ function PublishAsUserCallBack(err) { } //指定发送的用户 -var userId = 100; +let userId = 100; //发布公共事件 CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); @@ -353,10 +353,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac ```js -var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 //订阅者信息 -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -398,10 +398,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\): **示例:** ```js -var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 //订阅者信息 -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -549,7 +549,7 @@ getCode(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取有序公共事件的结果代码回调 function getCodeCallback(err, Code) { @@ -579,7 +579,7 @@ getCode(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.getCode().then((Code) => { console.info("getCode " + JSON.stringify(Code)); @@ -606,7 +606,7 @@ setCode(code: number, callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //设置有序公共事件的结果代码回调 function setCodeCallback(err) { @@ -642,7 +642,7 @@ setCode(code: number): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.setCode(1).then(() => { console.info("setCode"); @@ -668,7 +668,7 @@ getData(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取有序公共事件的结果数据回调 function getDataCallback(err, Data) { @@ -698,7 +698,7 @@ getData(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.getData().then((Data) => { console.info("getData " + JSON.stringify(Data)); @@ -725,7 +725,7 @@ setData(data: string, callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //设置有序公共事件的结果数据回调 function setDataCallback(err) { @@ -761,7 +761,7 @@ setData(data: string): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.setData("publish_data_changed").then(() => { console.info("setData"); @@ -789,7 +789,7 @@ setCodeAndData(code: number, data: string, callback:AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //设置有序公共事件的结果代码和结果数据回调 function setCodeDataCallback(err) { @@ -826,7 +826,7 @@ setCodeAndData(code: number, data: string): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); @@ -854,7 +854,7 @@ isOrderedCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取当前公共事件是否为有序事件的回调 function isOrderedCallback(err, isOrdered) { @@ -886,7 +886,7 @@ isOrderedCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); @@ -914,7 +914,7 @@ isStickyCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取当前公共事件是否为粘性事件的回调 function isStickyCallback(err, isSticky) { @@ -946,7 +946,7 @@ isStickyCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); @@ -972,7 +972,7 @@ abortCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //取消当前有序公共事件的回调 function abortCallback(err) { @@ -1002,7 +1002,7 @@ abortCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); @@ -1028,7 +1028,7 @@ clearAbortCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //清除当前公共事件取消状态的回调 function clearAbortCallback(err) { @@ -1058,7 +1058,7 @@ clearAbortCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); @@ -1084,7 +1084,7 @@ getAbortCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取当前有序公共事件是否取消的回调 function getAbortCallback(err, AbortCommonEvent) { @@ -1114,7 +1114,7 @@ getAbortCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); @@ -1140,7 +1140,7 @@ getSubscribeInfo(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //获取订阅者信息回调 function getSubscribeInfoCallback(err, SubscribeInfo) { @@ -1170,7 +1170,7 @@ getSubscribeInfo(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); @@ -1196,7 +1196,7 @@ finishCommonEvent(callback: AsyncCallback\): void **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 //结束当前有序公共事件的回调 function finishCommonEventCallback(err) { @@ -1226,7 +1226,7 @@ finishCommonEvent(): Promise\ **示例:** ```js -var subscriber; //创建成功的订阅者对象 +let subscriber; //创建成功的订阅者对象 subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); 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-cryptoFramework.md b/zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md index 889243b124f1d3a8213e2bd40faaab66a9e26cc8..5689f51f42b6eff47d583430da83dc53ddc650ff 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -23,7 +23,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" | INVALID_PARAMS | 401 | 非法入参。 | | NOT_SUPPORT | 801 | 操作不支持。 | | ERR_OUT_OF_MEMORY | 17620001 | 内存错误。 | -| ERR_EXTERNAL_ERROR | 17620002 | 运行时外部错误。 | +| ERR_RUNTIME_ERROR | 17620002 | 运行时外部错误。 | | ERR_CRYPTO_OPERATION | 17630001 | 调用三方算法库API出错。 | | ERR_CERT_SIGNATURE_FAILURE | 17630002 | 证书签名验证错误。 | | ERR_CERT_NOT_YET_VALID | 17630003 | 证书尚未生效。 | @@ -916,7 +916,7 @@ promiseGenerateRand.then(randData => { | ------- | ------ | ---- | ---- | ---------------------- | | iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为12字节| | aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节| -| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为16字节。
采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其作为解密时[GcmParamsSpec](#gcmparamsspec)中的authTag| +| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为16字节。
采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其末尾16字节作为解密时[GcmParamsSpec](#gcmparamsspec)中的authTag | ## CcmParamsSpec @@ -928,7 +928,7 @@ promiseGenerateRand.then(randData => { | ------- | -------- | ---- | ---- | -------------------------------| | iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为7字节 | | aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节 | -| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为12字节。
采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其作为解密时[CcmParamsSpec](#ccmparamsspec)中的authTag | +| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为12字节。
采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其末尾12字节作为解密时[CcmParamsSpec](#ccmparamsspec)中的authTag | ## CryptoMode @@ -1102,7 +1102,7 @@ key.clearMem(); createSymKeyGenerator(algName : string) : SymKeyGenerator -通过指定算法名称的字符串,获取相应的对称密钥生成器实例。 +通过指定算法名称的字符串,获取相应的对称密钥生成器实例。支持的对称密钥参数详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节中“生成密钥的字符串”。 **系统能力:** SystemCapability.Security.CryptoFramework @@ -1118,6 +1118,13 @@ createSymKeyGenerator(algName : string) : SymKeyGenerator | ----------------------------------- | -------------------------- | | [SymKeyGenerator](#symkeygenerator) | 返回对称密钥生成器的对象。 | +**示例:** + +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); +``` + ## SymKeyGenerator 对称密钥生成器。在使用该类的方法前,需要先使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)方法构建一个symKeyGenerator实例。 @@ -1367,7 +1374,7 @@ keyGenPromise.then( keyPair => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void -异步获取指定数据生成非对称密钥,通过注册回调函数获取结果。 +异步获取指定数据生成非对称密钥,通过注册回调函数获取结果。详情请看下方**密钥转换说明** **系统能力:** SystemCapability.Security.CryptoFramework @@ -1397,7 +1404,7 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ -异步获取指定数据生成非对称密钥,通过Promise获取结果。 +异步获取指定数据生成非对称密钥,通过Promise获取结果。详情请看下方**密钥转换说明** **系统能力:** SystemCapability.Security.CryptoFramework @@ -1428,10 +1435,18 @@ keyGenPromise.then( keyPair => { }); ``` +**密钥转换说明** + +1. RSA二进制密钥数据,按keysize(32位) ,nsize(keysize/8), esize(e实际长度),dsize(keysize/8),nval(大数n的二进制数据),eval(大数e的二进制数据),dval(大数d的二进制数据)拼接形成。 +2. RSA二进制密钥数据中,nsize和dsize为密钥位数/8,esize为具体的实际长度。 +3. RSA私钥数据需要包含keysize,nsize,esize,dsize,nval,eval,dval的全部数据,公钥材料中dsize设置为0,缺省dval的数据。 +4. RSA二进制密钥数据中,keysize、nsize、esize和dsize为32位二进制数据,数据的大小端格式请按设备CPU默认格式,密钥材料(nval、eval、dval)统一为大端格式。 +5. convertKey接口中,公钥和私钥二进制数据为可选项,可单独传入公钥或私钥的数据,生成对应只包含公钥或私钥的KeyPair对象。 + ## cryptoFramework.createCipher createCipher(transformation : string) : Cipher -通过指定算法名称,获取相应的[Cipher](#cipher)实例。 +通过指定算法名称,获取相应的[Cipher](#cipher)实例。支持的算法名参数详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节中的“指定算法名称字符串”。 **系统能力:** SystemCapability.Security.CryptoFramework @@ -1465,7 +1480,7 @@ try { ## Cipher -提供加解密的算法操作功能,按序调用本类中的[init()](#init-2)、[update()](#update-4)、[doFinal()](#dofinal-2)方法,可以实现对称加密/对称解密/非对称加密/非对称解密。 +提供加解密的算法操作功能,按序调用本类中的[init()](#init-2)、[update()](#update-4)、[doFinal()](#dofinal-2)方法,可以实现对称加密/对称解密/非对称加密/非对称解密。完整的加解密流程示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。 ### 属性 @@ -1630,7 +1645,7 @@ cipher.update(data).then((output) => { doFinal(data : DataBlob, callback : AsyncCallback\) : void -最后结束加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。如果在本次加解密过程中已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。
根据对称加解密的模式不同,doFinal的输出可能不同。
对于GCM和CCM模式的对称加密,在doFinal完成后需要将其结果暂存作为解密时的authTag。
对于其他模式的对称加解密,存在两种情况(1)update输出一部分加解密结果,doFinal输出剩余加解密结果;(2)update输出加解密结果全部由update输出,doFinal输出空。 +最后结束加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。如果在本次加解密过程中已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。
根据对称加解密的模式不同,doFinal的输出可能不同:
对于GCM和CCM模式的对称加密,doFinal的结果是剩余密文和authTag的拼接,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag(因此如果doFinal的data参数传入null,则doFinal的结果就是authTag)。在doFinal完成后需要将authTag暂存,填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec)。
对于其他模式的对称加解密,根据不同的模式特点,存在两种情况(1)update输出一部分加解密结果,doFinal输出剩余加解密结果;(2)加解密结果全部由update输出,doFinal输出空。 **系统能力:** SystemCapability.Security.CryptoFramework @@ -1662,7 +1677,7 @@ cipher.doFinal(data, (err, output) => { doFinal(data : DataBlob) : Promise\ -最后结束加密或者解密数据操作,通过Promise获取结果。如果在本次加解密过程中已经使用update传入过数据,可以在doFinal的data参数处传入null。 +最后结束加密或者解密数据操作,通过Promise获取结果。如果在本次加解密过程中已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。
根据对称加解密的模式不同,doFinal的输出可能不同:
对于GCM和CCM模式的对称加密,doFinal的结果是剩余密文和authTag的拼接,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag(因此如果doFinal的data参数传入null,则doFinal的结果就是authTag)。在doFinal完成后需要将authTag暂存,填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec)。
对于其他模式的对称加解密,根据不同的模式特点,存在两种情况(1)update输出一部分加解密结果,doFinal输出剩余加解密结果;(2)加解密结果全部由update输出,doFinal输出空。 **系统能力:** SystemCapability.Security.CryptoFramework @@ -2183,7 +2198,7 @@ createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : v | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | ------------------ | -| inStream | EncodingBlob | 是 | X509证书序列化数据 | +| inStream | [EncodingBlob](#encodingblob) | 是 | X509证书序列化数据 | | callback | AsyncCallback\ | 否 | 回调函数。表示X509证书对象 | @@ -2220,7 +2235,7 @@ createX509Cert(inStream : EncodingBlob) : Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------ | ---- | ------------------ | -| inStream | EncodingBlob | 是 | X509证书序列化数据 | +| inStream | [EncodingBlob](#encodingblob) | 是 | X509证书序列化数据 | **返回值**: @@ -2263,7 +2278,7 @@ verify(key : PubKey, callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | ------------------ | -| key | PubKey | 是 | 用于验签的公钥对象 | +| key | [PubKey](#pubkey) | 是 | 用于验签的公钥对象 | | callback | AsyncCallback\) | 否 | 回调函数。使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,不为null表示失败 | @@ -2309,7 +2324,7 @@ verify(key : PubKey) : Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------ | -| key | PubKey | 是 | 用于验签的公钥对象 | +| key | [PubKey](#pubkey) | 是 | 用于验签的公钥对象 | **返回值**: @@ -2355,7 +2370,7 @@ getEncoded(callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------- | -| callback | AsyncCallback\ | 否 | 回调函数。表示X509证书序列化数据 | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | 否 | 回调函数。表示X509证书序列化数据 | **示例**: @@ -2398,7 +2413,7 @@ getEncoded() : Promise\ | 类型 | 说明 | | ------------ | ---------------------- | -| Promise\ | 表示X509证书序列化数据 | +| Promise\<[EncodingBlob](#encodingblob)> | 表示X509证书序列化数据 | **示例**: @@ -2679,7 +2694,7 @@ getIssuerName() : DataBlob | 类型 | 说明 | | -------- | ---------------------- | -| DataBlob | 表示X509证书颁发者名称 | +| [DataBlob](#datablob) | 表示X509证书颁发者名称 | **示例**: @@ -2715,7 +2730,7 @@ getSubjectName() : DataBlob | 类型 | 说明 | | -------- | -------------------- | -| DataBlob | 表示X509证书主体名称 | +| [DataBlob](#datablob) | 表示X509证书主体名称 | **示例**: @@ -2823,7 +2838,7 @@ getSignature() : DataBlob | 类型 | 说明 | | -------- | -------------------- | -| DataBlob | 表示X509证书签名数据 | +| [DataBlob](#datablob) | 表示X509证书签名数据 | **示例**: @@ -2887,15 +2902,15 @@ cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) { getSignatureAlgOid() : string -表示获取X509证书签名算法OID。 +表示获取X509证书签名算法的对象标志符OID(Object Identifier)。OID是由国际标准组织(ISO)的名称注册机构分配。 **系统能力**:SystemCapability.Security.CryptoFramework **返回值**: -| 类型 | 说明 | -| ------ | ----------------------- | -| string | 表示X509证书签名算法OID | +| 类型 | 说明 | +| ------ | --------------------------------- | +| string | 表示X509证书签名算法对象标志符OID | **示例**: @@ -2931,7 +2946,7 @@ getSignatureAlgParams() : DataBlob | 类型 | 说明 | | -------- | ------------------------ | -| DataBlob | 表示X509证书签名算法参数 | +| [DataBlob](#datablob) | 表示X509证书签名算法参数 | **示例**: @@ -2967,7 +2982,7 @@ getKeyUsage() : DataBlob | 类型 | 说明 | | -------- | -------------------- | -| DataBlob | 表示X509证书秘钥用途 | +| [DataBlob](#datablob) | 表示X509证书秘钥用途 | **示例**: @@ -3003,7 +3018,7 @@ getExtKeyUsage() : DataArray | 类型 | 说明 | | --------- | ------------------------ | -| DataArray | 表示X509证书扩展秘钥用途 | +| [DataArray](#dataarray) | 表示X509证书扩展秘钥用途 | **示例**: @@ -3075,7 +3090,7 @@ getSubjectAltNames() : DataArray | 类型 | 说明 | | --------- | ------------------------ | -| DataArray | 表示X509证书主体可选名称 | +| [DataArray](#dataarray) | 表示X509证书主体可选名称 | **示例**: @@ -3111,7 +3126,7 @@ getIssuerAltNames() : DataArray | 类型 | 说明 | | --------- | -------------------------- | -| DataArray | 表示X509证书颁发者可选名称 | +| [DataArray](#dataarray) | 表示X509证书颁发者可选名称 | **示例**: @@ -3147,7 +3162,7 @@ createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------------------------- | -| inStream | EncodingBlob | 是 | 表示证书吊销列表序列化数据 | +| inStream | [EncodingBlob](#encodingblob) | 是 | 表示证书吊销列表序列化数据 | | callback | AsyncCallback\ | 否 | 回调函数。表示证书吊销列表对象 | @@ -3184,7 +3199,7 @@ createX509Crl(inStream : EncodingBlob) : Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------ | ---- | -------------------------- | -| inStream | EncodingBlob | 是 | 表示证书吊销列表序列化数据 | +| inStream | [EncodingBlob](#encodingblob) | 是 | 表示证书吊销列表序列化数据 | **返回值**: @@ -3227,7 +3242,7 @@ isRevoked(cert : X509Cert, callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------------------- | -| cert | X509Cert | 是 | 表示被检查的证书对象 | +| cert | [X509Cert](#x509cert) | 是 | 表示被检查的证书对象 | | callback | AsyncCallback\ | 否 | 回调函数。表示证书吊销状态,true表示已吊销,false表示未吊销 | @@ -3482,7 +3497,7 @@ verify(key : PubKey) : Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ---------------------- | -| key | PubKey | 是 | 表示用于验签的公钥对象 | +| key | [PubKey](#pubkey) | 是 | 表示用于验签的公钥对象 | **返回值**: @@ -3564,7 +3579,7 @@ getIssuerName() : DataBlob | 类型 | 说明 | | -------- | ------------------------------ | -| DataBlob | 表示X509证书吊销列表颁发者名称 | +| [DataBlob](#datablob) | 表示X509证书吊销列表颁发者名称 | **示例**: @@ -3937,7 +3952,7 @@ getTbsInfo(callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------- | -| callback | AsyncCallback\ | 否 | 回调函数。表示证书吊销列表的tbsCertList信息 | +| callback | AsyncCallback\<[DataBlob](#datablob)> | 否 | 回调函数。表示证书吊销列表的tbsCertList信息 | **示例**: @@ -3980,7 +3995,7 @@ getTbsInfo() : Promise\ | 类型 | 说明 | | -------- | --------------------------------- | -| Promise\ | 表示证书吊销列表的tbsCertList信息 | +| Promise\<[DataBlob](#datablob)> | 表示证书吊销列表的tbsCertList信息 | **示例**: @@ -4018,7 +4033,7 @@ getSignature() : DataBlob | 类型 | 说明 | | -------- | ------------------------------ | -| DataBlob | 表示X509证书吊销列表的签名数据 | +| [DataBlob](#datablob) | 表示X509证书吊销列表的签名数据 | **示例**: @@ -4082,15 +4097,15 @@ cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) { getSignatureAlgOid() : string -表示获取X509证书吊销列表签名的算法OID。 +表示获取X509证书吊销列表签名算法的对象标志符OID(Object Identifier)。OID是由国际标准组织(ISO)的名称注册机构分配。 **系统能力**:SystemCapability.Security.CryptoFramework **返回值**: -| 类型 | 说明 | -| ------ | ----------------------------------- | -| string | 表示X509证书吊销列表签名的算法OID。 | +| 类型 | 说明 | +| ------ | --------------------------------------------- | +| string | 表示X509证书吊销列表签名算法的对象标志符OID。 | **示例**: @@ -4126,7 +4141,7 @@ getSignatureAlgParams() : DataBlob | 类型 | 说明 | | -------- | ---------------------------------- | -| DataBlob | 表示X509证书吊销列表签名的算法参数 | +| [DataBlob](#datablob) | 表示X509证书吊销列表签名的算法参数 | **示例**: @@ -4160,9 +4175,9 @@ createCertChainValidator(algorithm :string) : CertChainValidator **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | -------------------- | -| algorithm | string | 是 | 表示证书链校验器算法 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ------------------------------------------ | +| algorithm | string | 是 | 表示证书链校验器算法。当前仅支持输入“PKIX” | **返回值**: @@ -4187,6 +4202,7 @@ let validator = cryptoFramework.createCertChainValidator("PKIX"); validate(certChain : CertChainData, callback : AsyncCallback\) : void 表示校验X509证书链。 +由于端侧系统时间不可信,证书链校验不包含对证书有效时间的校验。如果需要检查证书的时间有效性,可使用X509证书的[checkValidityWithDate](#checkvaliditywithdate)方法进行检查。详见[证书规格](../../security/cryptoFramework-overview.md#证书规格) **系统能力**:SystemCapability.Security.CryptoFramework @@ -4194,7 +4210,7 @@ validate(certChain : CertChainData, callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------- | ---- | ------------------------ | -| certChain | CertChainData | 是 | 表示X509证书链序列化数据 | +| certChain | [CertChainData](#certchaindata) | 是 | 表示X509证书链序列化数据 | | callback | AsyncCallback\ | 否 | 回调函数。使用AsyncCallback的第一个error参数判断是否校验成功,error为null表示成功,error不为null表示失败 | @@ -4228,6 +4244,7 @@ validator.validate(certChainData, function (error, data) { validate(certChain : CertChainData) : Promise\ 表示校验X509证书链。 +由于端侧系统时间不可信,证书链校验不包含对证书有效时间的校验。如果需要检查证书的时间有效性,可使用X509证书的[checkValidityWithDate](#checkvaliditywithdate)方法进行检查。详见[证书规格](../../security/cryptoFramework-overview.md#证书规格) **系统能力**:SystemCapability.Security.CryptoFramework @@ -4235,7 +4252,7 @@ validate(certChain : CertChainData) : Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------- | ---- | ------------------------ | -| certChain | CertChainData | 是 | 表示X509证书链序列化数据。使用AsyncCallback的第一个error参数判断是否校验成功,error为null表示成功,error不为null表示失败 | +| certChain | [CertChainData](#certchaindata) | 是 | 表示X509证书链序列化数据。 | **返回值**: @@ -4305,7 +4322,7 @@ getEncoded(callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------- | -| callback | AsyncCallback\ | 否 | 回调函数。表示被吊销证书的序列化数据 | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | 否 | 回调函数。表示被吊销证书的序列化数据 | **示例**: @@ -4336,7 +4353,7 @@ getEncoded() : Promise\ | 类型 | 说明 | | ------------ | -------------------------- | -| Promise\ | 表示被吊销证书的序列化数据 | +| Promise\<[EncodingBlob](#encodingblob)> | 表示被吊销证书的序列化数据 | **示例**: @@ -4388,7 +4405,7 @@ getCertIssuer(callback : AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | -------- | -| callback | AsyncCallback\ | 否 | 回调函数。表示被吊销证书的颁发者信息 | +| callback | AsyncCallback\<[DataBlob](#datablob)> | 否 | 回调函数。表示被吊销证书的颁发者信息 | **示例**: @@ -4419,7 +4436,7 @@ getCertIssuer() : Promise\ | 类型 | 说明 | | -------- | -------------------------- | -| Promise\ | 表示被吊销证书的颁发者信息 | +| Promise\<[DataBlob](#datablob)> | 表示被吊销证书的颁发者信息 | **示例**: 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-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..28e346734f8157fcd47ddbd815f089bf52baaa5f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -376,9 +376,9 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callba ```ts var parameter = { - srcDeviceId: localDeviceId - dstDeviceId: remoteDeviceId - missionId: remoteMissionId + srcDeviceId: localDeviceId, + dstDeviceId: remoteDeviceId, + missionId: remoteMissionId, wantParams: {"key": "value"} }; function OnContinueDone(resultCode) { @@ -426,9 +426,9 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promi ```ts var parameter = { - srcDeviceId: localDeviceId - dstDeviceId: remoteDeviceId - missionId: remoteMissionId + srcDeviceId: localDeviceId, + dstDeviceId: remoteDeviceId, + missionId: remoteMissionId, wantParams: {"key": "value"} }; function OnContinueDone(resultCode) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-emitter.md b/zh-cn/application-dev/reference/apis/js-apis-emitter.md index 989bd312f6990d5fcf39b278710939057ef2e1de..7c422e7985c55146344c7b2a165f8c8adea58cd6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-emitter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-emitter.md @@ -26,10 +26,10 @@ on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | 是 | 持续订阅的事件 | -| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | 是 | 持续订阅的事件,其中EventPriority不生效 | +| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | **示例:** @@ -53,10 +53,10 @@ once(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdat **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | 是 | 单次订阅的事件 | -| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | 是 | 单次订阅的事件,其中EventPriority不生效 | +| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | **示例:** 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-hisysevent.md b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md index 174ec0ebb77cd895952b59a0939689749c7da52d..1895a0eb1687b281cd3f8fe211f26f850f284f9d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @@ -60,20 +60,24 @@ write(info: SysEventInfo, callback: AsyncCallback<void>): void ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` @@ -102,26 +106,30 @@ write(info: SysEventInfo): Promise<void> ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}).then( - (val) => { - // do something here. - } -).catch( - (err) => { - // do something here. - } -) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }).then( + (val) => { + // do something here. + } + ).catch( + (err) => { + // do something here. + } + ) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` ## RuleType @@ -177,32 +185,30 @@ addWatcher(watcher: Watcher): number | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | 是 | 系统事件订阅者对象。 | -**返回值:** - -| 类型 | 说明 | -| ------- | -------------------------------------------------- | -| number | 系统事件订阅结果。
- 0表示订阅成功。
- 负值表示订阅失败。 | - **示例:** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + hiSysEvent.addWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) ``` ## hiSysEvent.removeWatcher @@ -221,33 +227,31 @@ removeWatcher(watcher: Watcher): number | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | 是 | 系统事件订阅者对象。 | -**返回值:** - -| 类型 | 说明 | -| ------- | ----------------------------------------------------------- | -| number | 取消订阅系统事件的结果。
- 0表示取消订阅成功。
- 负值表示取消订阅失败。 | - **示例:** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + let ret = hiSysEvent.addWatcher(watcher) + hiSysEvent.removeWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) -hiSysEvent.removeWatcher(watcher) ``` ## QueryArg @@ -281,7 +285,7 @@ hiSysEvent.removeWatcher(watcher) | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| onQuery | function | 是 | 返回查询到的系统事件的回调方法(infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void。 | +| onQuery | function | 是 | 返回查询到的系统事件的回调方法(infos: [SysEventInfo](#syseventinfo)[]) => void。 | | onComplete | function | 是 | 查询结果统计的回调方法(reason: number, total: number) => void。 | ## hiSysEvent.query @@ -302,44 +306,42 @@ query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number | rules | [QueryRule](#queryrule)[] | 是 | 查询规则数组,每次查询可配置多个查询规则。 | | querier | [Querier](#querier) | 是 | 查询者对象,包含查询结果及结束的相关回调。 | -**返回值:** - -| 类型 | 说明 | -| ------- | ----------------------------------------------------------- | -| number | 系统事件查询的结果。
- 0表示查询成功.
- 负值表示查询失败。 | - **示例:** ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) -hiSysEvent.query({ - beginTime: -1, - endTime: -1, - maxEvents: 5, -}, [{ - domain: "RELIABILITY", - names: ["STACK"], -}], { - onQuery: function (infos, seqs) { - // do something here. - }, - onComplete: function(reason, total) { - // do something here. - } -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) + hiSysEvent.query({ + beginTime: -1, + endTime: -1, + maxEvents: 5, + }, [{ + domain: "RELIABILITY", + names: ["STACK"], + }], { + onQuery: function (infos) { + // do something here. + }, + onComplete: function(reason, total) { + // do something here. + } + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` \ No newline at end of file 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-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index dab4a75c0a4ee4f5079cfd0fcce5497b76be0abc..32319b0f5e36631db7f00257255834b220947330 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -52,7 +52,7 @@ createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 回调函数。异步返回VideoPlayer实例,可用于管理和播放视频媒体。 | +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 回调函数。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | **示例:** @@ -79,9 +79,9 @@ createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)> **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ----------------------------------- | -| Promise<[VideoPlayer](#videoplayer8)> | Promise对象。异步返回VideoPlayer实例,可用于管理和播放视频媒体。 | +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------------------------------ | +| Promise<[VideoPlayer](#videoplayer8)> | Promise对象。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | **示例:** @@ -111,9 +111,9 @@ createAudioRecorder(): AudioRecorder **返回值:** -| 类型 | 说明 | -| ------------------------------- | ----------------------------------------- | -| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。 | +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。可用于录制音频媒体。 | **示例:** @@ -134,7 +134,7 @@ createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | 是 | 回调函数。异步返回VideoRecorder实例,可用于录制视频媒体。 | +| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | 是 | 回调函数。异步返回VideoRecorder实例,失败时返回null。可用于录制视频媒体。 | **示例:** @@ -162,9 +162,9 @@ createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> **返回值:** -| 类型 | 说明 | -| ----------------------------------------- | ----------------------------------- | -| Promise<[VideoRecorder](#videorecorder9)> | Promise对象。异步返回VideoRecorder实例,可用于录制视频媒体。 | +| 类型 | 说明 | +| ----------------------------------------- | ------------------------------------------------------------ | +| Promise<[VideoRecorder](#videorecorder9)> | Promise对象。异步返回VideoRecorder实例,失败时返回null。可用于录制视频媒体。 | **示例:** @@ -361,9 +361,9 @@ seek(timeMs: number): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms)。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------------------------------------------------- | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围[0, duration]。 | **示例:** @@ -426,9 +426,9 @@ getTrackDescription(callback: AsyncCallback>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | 是 | 获取音频轨道信息回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback> | 是 | 音频轨道信息MediaDescription数组回调方法。 | **示例:** @@ -462,9 +462,9 @@ getTrackDescription(): Promise> **返回值:** -| 类型 | 说明 | -| ------------------------------------------------------ | ------------------------------- | -| Promise> | 获取音频轨道信息Promise返回值。 | +| 类型 | 说明 | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | 音频轨道信息MediaDescription数组Promise返回值。 | **示例:** @@ -496,7 +496,7 @@ for (let i = 0; i < arrayDescription.length; i++) { on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -开始订阅音频缓存更新事件。 +开始订阅音频缓存更新事件。仅网络播放支持该订阅事件。 **系统能力:** SystemCapability.Multimedia.Media.AudioPlayer @@ -593,7 +593,7 @@ audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 on(type: 'timeUpdate', callback: Callback\): void -开始订阅音频播放时间更新事件。 +开始订阅音频播放时间更新事件。处于播放状态时,每隔1s上报一次该事件。 **系统能力:** SystemCapability.Multimedia.Media.AudioPlayer @@ -1013,10 +1013,10 @@ seek(timeMs: number, callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms)。 | -| callback | function | 是 | 跳转到指定播放位置的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| callback | function | 是 | 跳转到指定播放位置的回调方法。 | **示例:** @@ -1041,11 +1041,11 @@ seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms)。 | -| mode | [SeekMode](#seekmode8) | 是 | 跳转模式。 | -| callback | function | 是 | 跳转到指定播放位置的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| mode | [SeekMode](#seekmode8) | 是 | 跳转模式。 | +| callback | function | 是 | 跳转到指定播放位置的回调方法。 | **示例:** @@ -1071,16 +1071,16 @@ seek(timeMs: number, mode?:SeekMode): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------------- | ---- | ------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms)。 | -| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 | **返回值:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 跳转到指定播放位置的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------------------------- | +| Promise\ | 跳转到指定播放位置的Promise返回值,单位ms。 | **示例:** @@ -1219,9 +1219,9 @@ getTrackDescription(callback: AsyncCallback>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | 是 | 获取视频轨道信息回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback> | 是 | 视频轨道信息MediaDescription数组回调方法。 | **示例:** @@ -1255,9 +1255,9 @@ getTrackDescription(): Promise> **返回值:** -| 类型 | 说明 | -| ------------------------------------------------------ | ------------------------------- | -| Promise> | 获取视频轨道信息Promise返回值。 | +| 类型 | 说明 | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | 视频轨道信息MediaDescription数组Promise返回值。 | **示例:** @@ -1331,9 +1331,9 @@ setSpeed(speed:number): Promise\ **返回值:** -| 类型 | 说明 | -| ---------------- | ------------------------- | -| Promise\ | 通过Promise获取设置结果。 | +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | 播放速度Promise返回值,具体见[PlaybackSpeed](#playbackspeed8)。 | **示例:** @@ -1388,13 +1388,13 @@ selectBitrate(bitrate:number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | -------------------------------------------- | -| bitrate | number | 是 | 指定码率播放,用于hls多码率场景,单位为bps。 | +| bitrate | number | 是 | 指定播放码率,用于hls多码率场景,单位为bps。 | **返回值:** -| 类型 | 说明 | -| ---------------- | ------------------------- | -| Promise\ | 通过Promise获取设置结果。 | +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise\ | 指定播放码率Promise返回值。 | **示例:** @@ -1434,7 +1434,7 @@ videoPlayer.on('playbackCompleted', () => { on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void -开始监听视频缓存更新事件。 +开始监听视频缓存更新事件。仅网络播放支持该订阅事件。 **系统能力:** SystemCapability.Multimedia.Media.VideoPlayer diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index da1b64893711283291529e72b1f4c255f8f29cf3..454ff579051073954699875f933493f999809aad 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -34,7 +34,11 @@ publish(request: NotificationRequest, callback: AsyncCallback\): void ```js //publish回调 function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } //通知Request对象 var notificationRequest = { @@ -83,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -113,7 +117,11 @@ publish(request: NotificationRequest, userId: number, callback: AsyncCallback\publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // 接收通知的用户ID var userId = 1 @@ -169,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -195,7 +203,11 @@ cancel(id: number, label: string, callback: AsyncCallback\): void ```js //cancel回调 function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, "label", cancelCallback) ``` @@ -221,7 +233,7 @@ cancel(id: number, label?: string): Promise\ ```js Notification.cancel(0).then(() => { - console.info("==========================>cancelCallback=======================>"); + console.info("cancel sucess"); }); ``` @@ -247,7 +259,11 @@ cancel(id: number, callback: AsyncCallback\): void ```js //cancel回调 function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, cancelCallback) ``` @@ -273,7 +289,11 @@ cancelAll(callback: AsyncCallback\): void ```js //cancel回调 function cancelAllCallback(err) { - console.info("==========================>cancelAllCallback=======================>"); + if (err.code) { + console.info("cancelAll failed " + JSON.stringify(err)); + } else { + console.info("cancelAll success"); + } } Notification.cancelAll(cancelAllCallback) ``` @@ -292,7 +312,7 @@ cancelAll(): Promise\ ```js Notification.cancelAll().then(() => { - console.info("==========================>cancelAllCallback=======================>"); + console.info("cancelAll sucess"); }); ``` @@ -322,7 +342,11 @@ addSlot(slot: NotificationSlot, callback: AsyncCallback\): void ```js //addslot回调 function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } //通知slot对象 var notificationSlot = { @@ -359,7 +383,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -385,7 +409,11 @@ addSlot(type: SlotType, callback: AsyncCallback\): void ```js //addslot回调 function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) ``` @@ -410,7 +438,7 @@ addSlot(type: SlotType): Promise\ ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -440,7 +468,11 @@ addSlots(slots: Array\, callback: AsyncCallback\): voi ```js //addSlots回调 function addSlotsCallBack(err) { - console.info("==========================>addSlotsCallBack=======================>"); + if (err.code) { + console.info("addSlots failed " + JSON.stringify(err)); + } else { + console.info("addSlots success"); + } } //通知slot对象 var notificationSlot = { @@ -485,7 +517,7 @@ var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlots sucess"); }); ``` @@ -511,7 +543,11 @@ getSlot(slotType: SlotType, callback: AsyncCallback\): void ```js //getSlot回调 function getSlotCallback(err,data) { - console.info("==========================>getSlotCallback=======================>"); + if (err.code) { + console.info("getSlot failed " + JSON.stringify(err)); + } else { + console.info("getSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType, getSlotCallback) @@ -544,7 +580,7 @@ getSlot(slotType: SlotType): Promise\ ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("==========================>getSlotCallback=======================>"); + console.info("getSlot sucess, data: " + JSON.stringify(data)); }); ``` @@ -569,7 +605,11 @@ getSlots(callback: AsyncCallback>): void ```js //getSlots回调 function getSlotsCallback(err,data) { - console.info("==========================>getSlotsCallback=======================>"); + if (err.code) { + console.info("getSlots failed " + JSON.stringify(err)); + } else { + console.info("getSlots success"); + } } Notification.getSlots(getSlotsCallback) ``` @@ -594,7 +634,7 @@ getSlots(): Promise\> ```js Notification.getSlots().then((data) => { - console.info("==========================>getSlotsCallback=======================>"); + console.info("getSlots sucess, data: " + JSON.stringify(data)); }); ``` @@ -620,7 +660,11 @@ removeSlot(slotType: SlotType, callback: AsyncCallback\): void ```js //removeSlot回调 function removeSlotCallback(err) { - console.info("==========================>removeSlotCallback=======================>"); + if (err.code) { + console.info("removeSlot failed " + JSON.stringify(err)); + } else { + console.info("removeSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType,removeSlotCallback) @@ -647,7 +691,7 @@ removeSlot(slotType: SlotType): Promise\ ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("==========================>removeSlotCallback=======================>"); + console.info("removeSlot sucess"); }); ``` @@ -671,7 +715,11 @@ removeAllSlots(callback: AsyncCallback\): void ```js function removeAllCallBack(err) { - console.info("================>removeAllCallBack=======================>"); + if (err.code) { + console.info("removeAllSlots failed " + JSON.stringify(err)); + } else { + console.info("removeAllSlots success"); + } } Notification.removeAllSlots(removeAllCallBack) ``` @@ -690,7 +738,7 @@ removeAllSlots(): Promise\ ```js Notification.removeAllSlots().then(() => { - console.info("==========================>removeAllCallBack=======================>"); + console.info("removeAllSlots sucess"); }); ``` @@ -721,10 +769,14 @@ subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, c ```js //subscribe回调 function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -760,10 +812,14 @@ subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): ```js function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -796,13 +852,17 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): ```js function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("==========================>subscribeCallback=======================>"); + console.info("subscribe sucess"); }); ``` @@ -831,13 +891,17 @@ unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) ```js function unsubscribeCallback(err) { - console.info("==========================>unsubscribeCallback=======================>"); + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe success"); + } } -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -865,14 +929,14 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ **示例:** ```js -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("==========================>unsubscribeCallback=======================>"); + console.info("unsubscribe sucess"); }); ``` @@ -902,7 +966,11 @@ enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallbac ```js function enableNotificationCallback(err) { - console.info("==========================>enableNotificationCallback=======================>"); + if (err.code) { + console.info("enableNotification failed " + JSON.stringify(err)); + } else { + console.info("enableNotification success"); + } } var bundle = { bundle: "bundleName1", @@ -938,7 +1006,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("==========================>enableNotificationCallback=======================>"); + console.info("enableNotification sucess"); }); ``` @@ -967,7 +1035,11 @@ isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } var bundle = { bundle: "bundleName1", @@ -1008,7 +1080,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1036,7 +1108,11 @@ isNotificationEnabled(callback: AsyncCallback\): void ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } Notification.isNotificationEnabled(isNotificationEnabledCallback); @@ -1072,7 +1148,7 @@ isNotificationEnabled(): Promise\ ```js Notification.isNotificationEnabled().then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1102,7 +1178,11 @@ displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\displayBadgeCallback=======================>"); + if (err.code) { + console.info("displayBadge failed " + JSON.stringify(err)); + } else { + console.info("displayBadge success"); + } } var bundle = { bundle: "bundleName1", @@ -1138,7 +1218,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("==========================>displayBadgeCallback=======================>"); + console.info("displayBadge sucess"); }); ``` @@ -1167,7 +1247,11 @@ isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void ```js function isBadgeDisplayedCallback(err, data) { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + if (err.code) { + console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + } else { + console.info("isBadgeDisplayed success"); + } } var bundle = { bundle: "bundleName1", @@ -1208,7 +1292,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); }); ``` @@ -1238,7 +1322,11 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCal ```js function setSlotByBundleCallback(err) { - console.info("==========================>setSlotByBundleCallback=======================>"); + if (err.code) { + console.info("setSlotByBundle failed " + JSON.stringify(err)); + } else { + console.info("setSlotByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1280,7 +1368,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("==========================>setSlotByBundleCallback=======================>"); + console.info("setSlotByBundle sucess"); }); ``` @@ -1309,7 +1397,11 @@ getSlotsByBundle(bundle: BundleOption, callback: AsyncCallbackgetSlotsByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotsByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotsByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1350,7 +1442,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("==========================>getSlotsByBundleCallback=======================>"); + console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1379,7 +1471,11 @@ getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): voi ```js function getSlotNumByBundleCallback(err, data) { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotNumByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1420,7 +1516,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1451,7 +1547,11 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea ```js function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } var bundle = { bundle: "bundleName1", @@ -1498,7 +1598,7 @@ var notificationKey = { } var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason).then(() => { - console.info("==========================>removeCallback=======================>"); + console.info("remove sucess"); }); ``` @@ -1530,7 +1630,11 @@ remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): var hashCode = 'hashCode' function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } var reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; Notification.remove(hashCode, reason, removeCallback); @@ -1563,7 +1667,7 @@ remove(hashCode: string, reason: RemoveReason): Promise\ var hashCode = 'hashCode' var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(hashCode, reason).then(() => { - console.info("==========================>removeCallback=======================>"); + console.info("remove sucess"); }); ``` @@ -1592,7 +1696,11 @@ removeAll(bundle: BundleOption, callback: AsyncCallback\): void ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var bundle = { bundle: "bundleName1", @@ -1624,7 +1732,11 @@ removeAll(callback: AsyncCallback\): void ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } Notification.removeAll(removeAllCallback); @@ -1654,7 +1766,7 @@ removeAll(bundle?: BundleOption): Promise\ ```js Notification.removeAll().then(() => { - console.info("==========================>removeAllCallback=======================>"); + console.info("removeAll sucess"); }); ``` @@ -1681,7 +1793,11 @@ removeAll(userId: number, callback: AsyncCallback\): void ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1711,7 +1827,11 @@ removeAll(userId: number): Promise\ ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1742,7 +1862,11 @@ getAllActiveNotifications(callback: AsyncCallback>) ```js function getAllActiveNotificationsCallback(err, data) { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getAllActiveNotifications success"); + } } Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); @@ -1772,7 +1896,7 @@ getAllActiveNotifications(): Promise\ { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); }); ``` @@ -1796,7 +1920,11 @@ getActiveNotificationCount(callback: AsyncCallback\): void ```js function getActiveNotificationCountCallback(err, data) { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + if (err.code) { + console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotificationCount success"); + } } Notification.getActiveNotificationCount(getActiveNotificationCountCallback); @@ -1822,7 +1950,7 @@ getActiveNotificationCount(): Promise\ ```js Notification.getActiveNotificationCount().then((data) => { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); }); ``` @@ -1846,7 +1974,11 @@ getActiveNotifications(callback: AsyncCallback>): v ```js function getActiveNotificationsCallback(err, data) { - console.info("==========================>getActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotifications success"); + } } Notification.getActiveNotifications(getActiveNotificationsCallback); @@ -1872,7 +2004,7 @@ getActiveNotifications(): Promise\ { - console.info("==========================>getActiveNotificationsCallback=======================>"); + console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1897,7 +2029,11 @@ cancelGroup(groupName: string, callback: AsyncCallback\): void ```js function cancelGroupCallback(err) { - console.info("==========================>cancelGroupCallback=======================>"); + if (err.code) { + console.info("cancelGroup failed " + JSON.stringify(err)); + } else { + console.info("cancelGroup success"); + } } var groupName = "GroupName"; @@ -1926,7 +2062,7 @@ cancelGroup(groupName: string): Promise\ ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("==========================>cancelGroupPromise=======================>"); + console.info("cancelGroup sucess"); }); ``` @@ -1956,7 +2092,11 @@ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCall ```js function removeGroupByBundleCallback(err) { - console.info("==========================>removeGroupByBundleCallback=======================>"); + if (err.code) { + console.info("removeGroupByBundle failed " + JSON.stringify(err)); + } else { + console.info("removeGroupByBundle success"); + } } var bundleOption = {bundle: "Bundle"}; @@ -1992,7 +2132,7 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("==========================>removeGroupByBundlePromise=======================>"); + console.info("removeGroupByBundle sucess"); }); ``` @@ -2021,7 +2161,11 @@ setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): vo ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2062,7 +2206,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2091,7 +2235,11 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallb ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2138,7 +2286,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2165,7 +2313,11 @@ getDoNotDisturbDate(callback: AsyncCallback\): void ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); @@ -2195,7 +2347,7 @@ getDoNotDisturbDate(): Promise\ ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2223,7 +2375,11 @@ getDoNotDisturbDate(userId: number, callback: AsyncCallback\) ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } var userId = 1 @@ -2263,7 +2419,7 @@ getDoNotDisturbDate(userId: number): Promise\ var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2290,7 +2446,11 @@ supportDoNotDisturbMode(callback: AsyncCallback\): void ```js function supportDoNotDisturbModeCallback(err,data) { - console.info("==========================>supportDoNotDisturbModeCallback=======================>"); + if (err.code) { + console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + } else { + console.info("supportDoNotDisturbMode success"); + } } Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); @@ -2320,7 +2480,7 @@ supportDoNotDisturbMode(): Promise\ ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("==========================>supportDoNotDisturbModePromise=======================>"); + console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); }); ``` @@ -2346,7 +2506,11 @@ isSupportTemplate(templateName: string, callback: AsyncCallback\): voi ```javascript var templateName = 'process'; function isSupportTemplateCallback(err, data) { - console.info("isSupportTemplateCallback"); + if (err.code) { + console.info("isSupportTemplate failed " + JSON.stringify(err)); + } else { + console.info("isSupportTemplate success"); + } } Notification.isSupportTemplate(templateName, isSupportTemplateCallback); @@ -2380,7 +2544,7 @@ isSupportTemplate(templateName: string): Promise\ var templateName = 'process'; Notification.isSupportTemplate(templateName).then((data) => { - console.info("isSupportTemplateCallback"); + console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` @@ -2404,7 +2568,11 @@ requestEnableNotification(callback: AsyncCallback\): void ```javascript function requestEnableNotificationCallback() { - console.log('------------- requestEnabledNotification --------------'); + if (err.code) { + console.info("requestEnableNotification failed " + JSON.stringify(err)); + } else { + console.info("requestEnableNotification success"); + } }; Notification.requestEnableNotification(requestEnableNotificationCallback); @@ -2425,7 +2593,7 @@ requestEnableNotification(): Promise\ ```javascript Notification.requestEnableNotification() .then(() => { - console.info("requestEnableNotification "); + console.info("requestEnableNotification sucess"); }); ``` @@ -2453,7 +2621,11 @@ enableDistributed(enable: boolean, callback: AsyncCallback\): void ```javascript function enabledNotificationCallback() { - console.log('----------- enableDistributed ------------'); + if (err.code) { + console.info("enableDistributed failed " + JSON.stringify(err)); + } else { + console.info("enableDistributed success"); + } }; var enable = true @@ -2488,7 +2660,7 @@ var enable = true Notification.enableDistributed(enable) .then(() => { - console.log('-------- enableDistributed ----------'); + console.info("enableDistributed sucess"); }); ``` @@ -2511,7 +2683,11 @@ isDistributedEnabled(callback: AsyncCallback\): void ```javascript function isDistributedEnabledCallback() { - console.log('----------- isDistributedEnabled ------------'); + if (err.code) { + console.info("isDistributedEnabled failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabled success"); + } }; Notification.isDistributedEnabled(isDistributedEnabledCallback); @@ -2538,7 +2714,7 @@ isDistributedEnabled(): Promise\ ```javascript Notification.isDistributedEnabled() .then((data) => { - console.log('-------- isDistributedEnabled ----------'); + console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -2567,7 +2743,11 @@ enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: Async ```javascript function enableDistributedByBundleCallback() { - console.log('----------- enableDistributedByBundle ------------'); + if (err.code) { + console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + } else { + console.info("enableDistributedByBundle success"); + } }; var bundle = { @@ -2611,7 +2791,7 @@ var enable = true Notification.enableDistributedByBundle(bundle, enable) .then(() => { - console.log('-------- enableDistributedByBundle ----------'); + console.info("enableDistributedByBundle sucess"); }); ``` @@ -2638,7 +2818,11 @@ isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\ { - console.log('-------- isDistributedEnabledByBundle ----------', data); + console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -2710,7 +2894,11 @@ getDeviceRemindType(callback: AsyncCallback\): void ```javascript function getDeviceRemindTypeCallback(data) { - console.log('----------- getDeviceRemindType ------------', data); + if (err.code) { + console.info("getDeviceRemindType failed " + JSON.stringify(err)); + } else { + console.info("getDeviceRemindType success"); + } }; Notification.getDeviceRemindType(getDeviceRemindTypeCallback); @@ -2741,7 +2929,7 @@ getDeviceRemindType(): Promise\ ```javascript Notification.getDeviceRemindType() .then((data) => { - console.log('-------- getDeviceRemindType ----------', data); + console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); }); ``` @@ -2772,7 +2960,11 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user ```js //publishAsBundle回调 function publishAsBundleCallback(err) { - console.info("==========================>publishAsBundleCallback=======================>"); + if (err.code) { + console.info("publishAsBundle failed " + JSON.stringify(err)); + } else { + console.info("publishAsBundle success"); + } } // 被代理应用的包名 let representativeBundle = "com.example.demo" @@ -2836,7 +3028,7 @@ var notificationRequest = { } Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("==========================>publishAsBundleCallback=======================>"); + console.info("publishAsBundle sucess"); }); ``` @@ -2868,7 +3060,11 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number, callbac ```js //cancelAsBundle function cancelAsBundleCallback(err) { - console.info("==========================>cancelAsBundleCallback=======================>"); + if (err.code) { + console.info("cancelAsBundle failed " + JSON.stringify(err)); + } else { + console.info("cancelAsBundle success"); + } } // 被代理应用的包名 let representativeBundle = "com.example.demo" @@ -2909,7 +3105,7 @@ let representativeBundle = "com.example.demo" let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { - console.info("==========================>cancelAsBundleCallback=======================>"); + console.info("cancelAsBundle success"); }); ``` @@ -2939,7 +3135,11 @@ enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, ca ```js //enableNotificationSlot function enableSlotCallback(err) { - console.log('===================>enableSlotCallback==================>'); + if (err.code) { + console.info("enableNotificationSlot failed " + JSON.stringify(err)); + } else { + console.info("enableNotificationSlot success"); + } }; Notification.enableNotificationSlot( @@ -2977,7 +3177,7 @@ Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION, true).then(() => { - console.log('====================>enableNotificationSlot====================>'); + console.info("enableNotificationSlot sucess"); }); ``` @@ -3006,7 +3206,11 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncC ```js //isNotificationSlotEnabled function getEnableSlotCallback(err, data) { - console.log('===================>getEnableSlotCallback=================='); + if (err.code) { + console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationSlotEnabled success"); + } }; Notification.isNotificationSlotEnabled( @@ -3048,7 +3252,7 @@ Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION ).then((data) => { - console.log('====================>isNotificationSlotEnabled====================>'); + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3080,7 +3284,11 @@ let userId = 100; let enable = true; function setSyncNotificationEnabledWithoutAppCallback(err) { - console.log('setSyncNotificationEnabledWithoutAppCallback'); + if (err.code) { + console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + } else { + console.info("setSyncNotificationEnabledWithoutApp success"); + } } Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); @@ -3119,11 +3327,11 @@ let userId = 100; let enable = true; Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then((data) => { - console.log('setSyncNotificationEnabledWithoutApp'); + .then(() => { + console.info('setSyncNotificationEnabledWithoutApp'); }) .catch((err) => { - console.log('setSyncNotificationEnabledWithoutApp, err:', err); + console.info('setSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3154,9 +3362,9 @@ let userId = 100; function getSyncNotificationEnabledWithoutAppCallback(data, err) { if (err) { - console.log('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); } else { - console.log('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); } } @@ -3195,10 +3403,10 @@ let userId = 100; Notification.getSyncNotificationEnabledWithoutApp(userId) .then((data) => { - console.log('getSyncNotificationEnabledWithoutApp, data:', data); + console.info('getSyncNotificationEnabledWithoutApp, data:', data); }) .catch((err) => { - console.log('getSyncNotificationEnabledWithoutApp, err:', err); + console.info('getSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3242,7 +3450,7 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringify(data1)); + console.info('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { console.error('===> getWant failed because' + JSON.stringify(err)); 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-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index c187b3366cd892a42d791471a64fbf7d6ff23c9e..b1ad40aa1b6748ad6a11598526aae234055b3a09 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -27,7 +27,7 @@ getResourceManager(callback: AsyncCallback<ResourceManager>): void 获取当前应用的资源管理对象,使用callback形式返回ResourceManager对象。 -此接口仅可在FA模型下使用。 +**模型约束**:此接口仅可在FA模型下使用。 **系统能力**:SystemCapability.Global.ResourceManager @@ -60,7 +60,7 @@ getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManage 获取指定应用的资源管理对象,使用callback形式返回ResourceManager对象。 -此接口仅可在FA模型下使用。 +**模型约束**:此接口仅可在FA模型下使用。 **系统能力**:SystemCapability.Global.ResourceManager @@ -83,7 +83,7 @@ getResourceManager(): Promise<ResourceManager> 获取当前应用的资源管理对象,使用Promise形式返回ResourceManager对象。 -此接口仅可在FA模型下使用。 +**模型约束**:此接口仅可在FA模型下使用。 **系统能力**:SystemCapability.Global.ResourceManager @@ -114,7 +114,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager> 获取指定应用的资源管理对象,使用Promise形式返回ResourceManager对象。 -此接口仅可在FA模型下使用。 +**模型约束**:此接口仅可在FA模型下使用。 **系统能力**:SystemCapability.Global.ResourceManager @@ -261,10 +261,9 @@ resourceManager.getResourceManager((error, mgr) => { > > - 资源文件在工程的resources目录中定义,id可通过$r(资源地址).id的方式获取,例如$r('app.string.test').id。 +### getStringValue9+ -### getString - -getString(resId: number, callback: AsyncCallback<string>): void +getStringValue(resId: number, callback: AsyncCallback<string>): void 用户获取指定资源ID对应的字符串,使用callback形式返回字符串。 @@ -276,23 +275,35 @@ getString(resId: number, callback: AsyncCallback<string>): void | resId | number | 是 | 资源ID值 | | callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的字符串 | -**示例:** +**错误码:** + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + +**示例Stage:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getString($r('app.string.test').id, (error, value) => { + try { + this.context.getStringValue($r('app.string.test').id, (error, value) => { if (error != null) { console.log("error is " + error); } else { let str = value; } }); - }); + } catch (error) { + console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getString +### getStringValue9+ -getString(resId: number): Promise<string> +getStringValue(resId: number): Promise<string> 用户获取指定资源ID对应的字符串,使用Promise形式返回字符串。 @@ -308,21 +319,31 @@ getString(resId: number): Promise<string> | --------------------- | ----------- | | Promise<string> | 资源ID值对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getString($r('app.string.test').id).then(value => { - let str = value; - }).catch(error => { - console.log("getstring promise error is " + error); - }); - }); + try { + this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => { + let str = value; + }).catch(error => { + console.log("getStringValue promise error is " + error); + }); + } catch (error) { + console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getString9+ +### getStringValue9+ -getString(resource: Resource, callback: AsyncCallback<string>): void +getStringValue(resource: Resource, callback: AsyncCallback<string>): void 用户获取指定resource对象对应的字符串,使用callback形式返回字符串。 @@ -334,6 +355,14 @@ getString(resource: Resource, callback: AsyncCallback<string>): void | resource | [Resource](#resource9) | 是 | 资源信息 | | callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -341,18 +370,24 @@ getString(resource: Resource, callback: AsyncCallback<string>): void moduleName: "entry", id: $r('app.string.test').id }; - this.context.resourceManager.getString(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + tyr { + this.context.resourceManager.getStringValue(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` -### getString9+ -getString(resource: Resource): Promise<string> +### getStringValue9+ + +getStringValue(resource: Resource): Promise<string> 用户获取指定resource对象对应的字符串,使用Promise形式返回字符串。 @@ -368,6 +403,14 @@ getString(resource: Resource): Promise<string> | --------------------- | ---------------- | | Promise<string> | resource对象对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -375,16 +418,21 @@ getString(resource: Resource): Promise<string> moduleName: "entry", id: $r('app.string.test').id }; - this.context.resourceManager.getString(resource).then(value => { + try { + this.context.resourceManager.getStringValue(resource).then(value => { let str = value; - }).catch(error => { - console.log("getstring promise error is " + error); - }); + }).catch(error => { + console.log("getStringValue promise error is " + error); + }); + } catch (error) { + console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getStringArray -getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void +### getStringArrayValue9+ + +getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void 用户获取指定资源ID对应的字符串数组,使用callback形式返回字符串数组。 @@ -396,23 +444,33 @@ getStringArray(resId: number, callback: AsyncCallback<Array<string>> | resId | number | 是 | 资源ID值 | | callback | AsyncCallback<Array<string>> | 是 | 异步回调,用于返回获取的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getStringArray($r('app.strarray.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let strArray = value; - } - }); - }); + try { + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + } catch (error) { + console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getStringArray +### getStringArrayValue9+ -getStringArray(resId: number): Promise<Array<string>> +getStringArrayValue(resId: number): Promise<Array<string>> 用户获取指定资源ID对应的字符串数组,使用Promise形式返回字符串数组。 @@ -428,20 +486,30 @@ getStringArray(resId: number): Promise<Array<string>> | ---------------------------------- | ------------- | | Promise<Array<string>> | 资源ID值对应的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getStringArray($r('app.strarray.test').id).then(value => { - let strArray = value; - }).catch(error => { - console.log("getStringArray promise error is " + error); - }); - }); + try { + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArrayValue promise error is " + error); + }); + } catch (error) { + console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getStringArray9+ +### getStringArrayValue9+ -getStringArray(resource: Resource, callback: AsyncCallback<Array<string>>): void +getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void 用户获取指定resource对象对应的字符串数组,使用callback形式返回回字符串数组。 @@ -453,6 +521,14 @@ getStringArray(resource: Resource, callback: AsyncCallback<Array<string> | resource | [Resource](#resource9) | 是 | 资源信息 | | callback | AsyncCallback<Array<string>> | 是 | 异步回调,用于返回获取的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -460,18 +536,22 @@ getStringArray(resource: Resource, callback: AsyncCallback<Array<string> moduleName: "entry", id: $r('app.strarray.test').id }; - this.context.resourceManager.getStringArray(resource, (error, value) => { + try { + this.context.resourceManager.getStringArrayValue(resource, (error, value) => { if (error != null) { console.log("error is " + error); } else { let strArray = value; } - }); + }); + } catch (error) { + console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getStringArray9+ +### getStringArrayValue9+ -getStringArray(resource: Resource): Promise<Array<string>> +getStringArrayValue(resource: Resource): Promise<Array<string>> 用户获取指定resource对象对应的字符串数组,使用Promise形式返回字符串数组。 @@ -487,6 +567,14 @@ getStringArray(resource: Resource): Promise<Array<string>> | ---------------------------------- | ------------------ | | Promise<Array<string>> | resource对象对应的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -494,16 +582,21 @@ getStringArray(resource: Resource): Promise<Array<string>> moduleName: "entry", id: $r('app.strarray.test').id }; - this.context.resourceManager.getStringArray(resource).then(value => { + try { + this.context.resourceManager.getStringArrayValue(resource).then(value => { let strArray = value; - }).catch(error => { - console.log("getStringArray promise error is " + error); - }); + }).catch(error => { + console.log("getStringArray promise error is " + error); + }); + } catch (error) { + console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMedia -getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void +### getMediaContent + +getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void 用户获取指定资源ID对应的媒体文件内容,使用callback形式返回字节数组。 @@ -515,23 +608,32 @@ getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void | resId | number | 是 | 资源ID值 | | callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getMedia($r('app.media.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); - }); + try { + this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMedia +### getMediaContent -getMedia(resId: number): Promise<Uint8Array> +getMediaContent(resId: number): Promise<Uint8Array> 用户获取指定资源ID对应的媒体文件内容,使用Promise形式返回字节数组。 @@ -547,20 +649,29 @@ getMedia(resId: number): Promise<Uint8Array> | ------------------------- | -------------- | | Promise<Uint8Array> | 资源ID值对应的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getMedia($r('app.media.test').id).then(value => { + try { + mgr.getMediaContent($r('app.media.test').id).then(value => { let media = value; }).catch(error => { - console.log("getMedia promise error is " + error); + console.log("getMediaContent promise error is " + error); }); - }); + } catch (error) { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMedia9+ +### getMediaContent9+ -getMedia(resource: Resource, callback: AsyncCallback<Uint8Array>): void +getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void 用户获取指定resource对象对应的媒体文件内容,使用callback形式返回字节数组。 @@ -572,6 +683,13 @@ getMedia(resource: Resource, callback: AsyncCallback<Uint8Array>): void | resource | [Resource](#resource9) | 是 | 资源信息 | | callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts let resource = { @@ -579,18 +697,22 @@ getMedia(resource: Resource, callback: AsyncCallback<Uint8Array>): void moduleName: "entry", id: $r('app.media.test').id }; - this.context.resourceManager.getMedia(resource, (error, value) => { - if (error != null) { + try { + this.context.resourceManager.getMediaContent(resource, (error, value) => { + if (error != null) { console.log("error is " + error); - } else { + } else { let media = value; - } - }); + } + }); + } catch (error) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMedia9+ +### getMediaContent9+ -getMedia(resource: Resource): Promise<Uint8Array> +getMediaContent(resource: Resource): Promise<Uint8Array> 用户获取指定resource对象对应的媒体文件内容,使用Promise形式返回字节数组。 @@ -606,6 +728,13 @@ getMedia(resource: Resource): Promise<Uint8Array> | ------------------------- | ------------------- | | Promise<Uint8Array> | resource对象对应的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts let resource = { @@ -613,16 +742,21 @@ getMedia(resource: Resource): Promise<Uint8Array> moduleName: "entry", id: $r('app.media.test').id }; - this.context.resourceManager.getMedia(resource).then(value => { + try { + this.context.resourceManager.getMediaContent(resource).then(value => { let media = value; - }).catch(error => { - console.log("getMedia promise error is " + error); - }); + }).catch(error => { + console.log("getMediaContent promise error is " + error); + }); + } catch (error) { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMediaBase64 -getMediaBase64(resId: number, callback: AsyncCallback<string>): void +### getMediaContentBase64 + +getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void 用户获取指定资源ID对应的图片资源Base64编码,使用callback形式返回字符串。 @@ -634,23 +768,32 @@ getMediaBase64(resId: number, callback: AsyncCallback<string>): void | resId | number | 是 | 资源ID值 | | callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getMediaBase64($r('app.media.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); - }); + try { + mgr.getMediaContentBase64($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMediaBase64 +### getMediaContentBase64 -getMediaBase64(resId: number): Promise<string> +getMediaContentBase64(resId: number): Promise<string> 用户获取指定资源ID对应的图片资源Base64编码,使用Promise形式返回字符串。 @@ -666,20 +809,29 @@ getMediaBase64(resId: number): Promise<string> | --------------------- | -------------------- | | Promise<string> | 资源ID值对应的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getMediaBase64($r('app.media.test').id).then(value => { - let media = value; - }).catch(error => { - console.log("getMediaBase64 promise error is " + error); - }); - }); + try { + mgr.getMediaContentBase64($r('app.media.test').id).then(value => { + let media = value; + }).catch(error => { + console.log("getMediaContentBase64 promise error is " + error); + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMediaBase649+ +### getMediaContentBase649+ -getMediaBase64(resource: Resource, callback: AsyncCallback<string>): void +getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void 用户获取指定resource对象对应的图片资源Base64编码,使用callback形式返回字符串。 @@ -691,6 +843,13 @@ getMediaBase64(resource: Resource, callback: AsyncCallback<string>): void | resource | [Resource](#resource9) | 是 | 资源信息 | | callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts let resource = { @@ -698,18 +857,22 @@ getMediaBase64(resource: Resource, callback: AsyncCallback<string>): void moduleName: "entry", id: $r('app.media.test').id }; - this.context.resourceManager.getMediaBase64(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + try { + this.context.resourceManager.getMediaContentBase64(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getMediaBase649+ +### getMediaContentBase649+ -getMediaBase64(resource: Resource): Promise<string> +getMediaContentBase64(resource: Resource): Promise<string> 用户获取指定resource对象对应的图片资源Base64编码,使用Promise形式返回字符串。 @@ -725,6 +888,13 @@ getMediaBase64(resource: Resource): Promise<string> | --------------------- | ------------------------- | | Promise<string> | resource对象对应的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | + **示例:** ```ts let resource = { @@ -732,11 +902,15 @@ getMediaBase64(resource: Resource): Promise<string> moduleName: "entry", id: $r('app.media.test').id }; - this.context.resourceManager.getMediaBase64(resource).then(value => { - let media = value; - }).catch(error => { - console.log("getMediaBase64 promise error is " + error); - }); + try { + this.context.resourceManager.getMediaContentBase64(resource).then(value => { + let media = value; + }).catch(error => { + console.log("getMediaContentBase64 promise error is " + error); + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } ``` @@ -848,9 +1022,9 @@ getDeviceCapability(): Promise<DeviceCapability> ``` -### getPluralString +### getPluralStringValue -getPluralString(resId: number, num: number, callback: AsyncCallback<string>): void +getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void 根据指定数量获取指定ID字符串表示的单复数字符串,使用callback形式返回字符串。 @@ -863,23 +1037,33 @@ getPluralString(resId: number, num: number, callback: AsyncCallback<string> | num | number | 是 | 数量值 | | callback | AsyncCallback<string> | 是 | 异步回调,返回根据指定数量获取指定ID字符串表示的单复数字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); - }); + try { + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getPluralString +### getPluralStringValue -getPluralString(resId: number, num: number): Promise<string> +getPluralStringValue(resId: number, num: number): Promise<string> 根据指定数量获取对指定ID字符串表示的单复数字符串,使用Promise形式返回字符串。 @@ -896,20 +1080,30 @@ getPluralString(resId: number, num: number): Promise<string> | --------------------- | ------------------------- | | Promise<string> | 根据提供的数量获取对应ID字符串表示的单复数字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getPluralString($r("app.plural.test").id, 1).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralString promise error is " + error); - }); - }); + try { + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralStringValue promise error is " + error); + }); + } catch (error) { + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getPluralString9+ +### getPluralStringValue9+ -getPluralString(resource: Resource, num: number, callback: AsyncCallback<string>): void +getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void 根据指定数量获取指定resource对象表示的单复数字符串,使用callback形式返回字符串。 @@ -922,6 +1116,14 @@ getPluralString(resource: Resource, num: number, callback: AsyncCallback<stri | num | number | 是 | 数量值 | | callback | AsyncCallback<string> | 是 | 异步回调,返回根据指定数量获取指定resource对象表示的单复数字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -929,13 +1131,18 @@ getPluralString(resource: Resource, num: number, callback: AsyncCallback<stri moduleName: "entry", id: $r('app.plural.test').id }; - this.context.resourceManager.getPluralString(resource, 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + try { + this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getPluralString9+ @@ -957,6 +1164,14 @@ getPluralString(resource: Resource, num: number): Promise<string> | --------------------- | ------------------------------ | | Promise<string> | 根据提供的数量获取对应resource对象表示的单复数字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -964,16 +1179,21 @@ getPluralString(resource: Resource, num: number): Promise<string> moduleName: "entry", id: $r('app.plural.test').id }; - this.context.resourceManager.getPluralString(resource, 1).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralString promise error is " + error); - }); + try { + this.context.resourceManager.getPluralString(resource, 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralString promise error is " + error); + }); + } catch (error) { + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getRawFile8+ -getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void +### getRawFileContent9+ + +getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void 用户获取resources/rawfile目录下对应的rawfile文件内容,使用callback形式返回字节数组。 @@ -985,22 +1205,31 @@ getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void | path | string | 是 | rawfile文件路径 | | callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的rawfile文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFile("test.xml", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - } - }); - }); + try { + this.context.resourceManager.getRawFileContent("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + } + }); + } catch (error) { + console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` -### getRawFile8+ +### getRawFileContent9+ -getRawFile(path: string): Promise<Uint8Array> +getRawFileContent(path: string): Promise<Uint8Array> 用户获取resources/rawfile目录下对应的rawfile文件内容,使用Promise形式返回字节数组。 @@ -1016,20 +1245,29 @@ getRawFile(path: string): Promise<Uint8Array> | ------------------------- | ----------- | | Promise<Uint8Array> | rawfile文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | + **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFile("test.xml").then(value => { - let rawFile = value; - }).catch(error => { - console.log("getRawFile promise error is " + error); - }); - }); + try { + this.context.resourceManager.getRawFileContent("test.xml").then(value => { + let rawFile = value; + }).catch(error => { + console.log("getRawFileContent promise error is " + error); + }); + } catch (error) { + console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`) + } ``` -### getRawFileDescriptor8+ -getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor>): void +### getRawFd9+ + +getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void 用户获取resources/rawfile目录下对应rawfile文件的descriptor,使用callback形式返回。 @@ -1039,26 +1277,34 @@ getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | 是 | rawfile文件路径 | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | +| callback | AsyncCallback<[getRawFd](#getrawfd9)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFileDescriptor("test.xml", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let fd = value.fd; - let offset = value.offset; - let length = value.length; - } - }); + try { + this.context.resourceManager.getRawFd("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + } + }); + } catch(error => { + console.log("getRawFd callback error is " + error); }); ``` -### getRawFileDescriptor8+ +### getRawFd9+ -getRawFileDescriptor(path: string): Promise<RawFileDescriptor> +getRawFd(path: string): Promise<RawFileDescriptor> 用户获取resources/rawfile目录下对应rawfile文件的descriptor,使用Promise形式返回。 @@ -1072,19 +1318,27 @@ getRawFileDescriptor(path: string): Promise<RawFileDescriptor> **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | rawfile文件descriptor | +| Promise<[getRawFd](#getrawfd9-1)> | rawfile文件descriptor | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | **示例:** ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFileDescriptor("test.xml").then(value => { - let fd = value.fd; - let offset = value.offset; - let length = value.length; - }).catch(error => { - console.log("getRawFileDescriptor promise error is " + error); - }); - }); + try { + this.context.resourceManager.getRawFd("test.xml").then(value => { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + }).catch(error => { + console.log("getRawFd promise error is " + error); + }); + } catch (error) { + console.log("getRawFd promise error is " + error); + }; ``` ### closeRawFileDescriptor8+ @@ -1141,55 +1395,140 @@ closeRawFileDescriptor(path: string): Promise<void> }); ``` -### release7+ - -release() - -用户释放创建的resourceManager。 -**系统能力**:SystemCapability.Global.ResourceManager +### closeRawFd9+ -**示例:** - ```ts - resourceManager.getResourceManager((error, mgr) => { - mgr.release(); - }); - ``` +closeRawFd(path: string, callback: AsyncCallback<void>): void -### getStringByName9+ +用户关闭resources/rawfile目录下rawfile文件的descriptor,使用callback形式返回。 -getStringByName(resName: string, callback: AsyncCallback<string>): void +**系统能力**:SystemCapability.Global.ResourceManager -用户获取指定资源名称对应的字符串,使用callback形式返回字符串。 +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------- | +| path | string | 是 | rawfile文件路径 | +| callback | AsyncCallback<void> | 是 | 异步回调 | -**系统能力**:SystemCapability.Global.ResourceManager +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | --------------- | -| resName | string | 是 | 资源名称 | -| callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的字符串 | +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | -**示例:** +**示例:** ```ts - this.context.resourceManager.getStringByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let string = value; - } - }); + try { + mgr.closeRawFd("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } + }); + } catch (error) { + console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` -### getStringByName9+ +### closeRawFd8+ -getStringByName(resName: string): Promise<string> +closeRawFd(path: string): Promise<void> -用户获取指定资源名称对应的字符串,使用Promise形式返回字符串。 +用户关闭resources/rawfile目录下rawfile文件的descriptor,使用Promise形式返回。 **系统能力**:SystemCapability.Global.ResourceManager -**参数:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ----------- | +| path | string | 是 | rawfile文件路径 | + +**返回值:** +| 类型 | 说明 | +| ------------------- | ---- | +| Promise<void> | 无返回值 | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | + +**示例:** + ```ts + try { + mgr.closeRawFd("test.xml").then(value => { + let result = value; + }).catch(error => { + console.log("closeRawFd promise error is " + error); + }); + } catch (error) { + console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### release7+ + +release() + +用户释放创建的resourceManager。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.release(); + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string, callback: AsyncCallback<string>): void + +用户获取指定资源名称对应的字符串,使用callback形式返回字符串。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | 是 | 资源名称 | +| callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的字符串 | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + +**示例:** + ```ts + try { + this.context.resourceManager.getStringByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } + }); + } catch (error) { + console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`) + } + + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +用户获取指定资源名称对应的字符串,使用Promise形式返回字符串。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1199,13 +1538,25 @@ getStringByName(resName: string): Promise<string> | --------------------- | ---------- | | Promise<string> | 资源名称对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getStringByName("test").then(value => { - let string = value; - }).catch(error => { - console.log("getStringByName promise error is " + error); - }); + try { + this.context.resourceManager.getStringByName("test").then(value => { + let string = value; + }).catch(error => { + console.log("getStringByName promise error is " + error); + }); + } catch (error) { + console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getStringArrayByName9+ @@ -1222,15 +1573,27 @@ getStringArrayByName(resName: string, callback: AsyncCallback<Array<string | resName | string | 是 | 资源名称 | | callback | AsyncCallback<Array<string>> | 是 | 异步回调,用于返回获取的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getStringArrayByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let strArray = value; - } - }); + try { + this.context.resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + } catch (error) { + console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getStringArrayByName9+ @@ -1251,13 +1614,25 @@ getStringArrayByName(resName: string): Promise<Array<string>> | ---------------------------------- | ------------ | | Promise<Array<string>> | 资源名称对应的字符串数组 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getStringArrayByName("test").then(value => { - let strArray = value; - }).catch(error => { - console.log("getStringArrayByName promise error is " + error); - }); + try { + this.context.resourceManager.getStringArrayByName("test").then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArrayByName promise error is " + error); + }); + } catch (error) { + console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getMediaByName9+ @@ -1274,15 +1649,27 @@ getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void | resName | string | 是 | 资源名称 | | callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getMediaByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + try { + this.context.resourceManager.getMediaByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getMediaByName9+ @@ -1303,13 +1690,25 @@ getMediaByName(resName: string): Promise<Uint8Array> | ------------------------- | ------------- | | Promise<Uint8Array> | 资源名称对应的媒体文件内容 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getMediaByName("test").then(value => { - let media = value; - }).catch(error => { - console.log("getMediaByName promise error is " + error); - }); + try { + this.context.resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaByName promise error is " + error); + }); + } catch (error) { + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getMediaBase64ByName9+ @@ -1326,15 +1725,27 @@ getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): vo | resName | string | 是 | 资源名称 | | callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getMediaBase64ByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + try { + this.context.resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getMediaBase64ByName9+ @@ -1355,13 +1766,25 @@ getMediaBase64ByName(resName: string): Promise<string> | --------------------- | ------------------- | | Promise<string> | 资源名称对应的图片资源Base64编码 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getMediaBase64ByName("test").then(value => { - let media = value; - }).catch(error => { - console.log("getMediaBase64ByName promise error is " + error); - }); + try { + this.context.resourceManager.getMediaBase64ByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); + } catch (error) { + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getPluralStringByName9+ @@ -1379,15 +1802,28 @@ getPluralStringByName(resName: string, num: number, callback: AsyncCallback<s | num | number | 是 | 数量值 | | callback | AsyncCallback<string> | 是 | 异步回调,返回根据传入的数量值获取资源名称对应的字符串资源 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + try { + this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getPluralStringByName9+ @@ -1409,13 +1845,25 @@ getPluralStringByName(resName: string, num: number): Promise<string> | --------------------- | ---------------------- | | Promise<string> | 根据传入的数量值获取资源名称对应的字符串资源 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getPluralStringByName("test", 1).then(value => { + try { + this.context.resourceManager.getPluralStringByName("test", 1).then(value => { let str = value; - }).catch(error => { + }).catch(error => { console.log("getPluralStringByName promise error is " + error); - }); + }); + } catch (error) { + console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getStringSync9+ @@ -1438,7 +1886,11 @@ getStringSync(resId: number): string **示例:** ```ts - this.context.resourceManager.getStringSync($r('app.string.test').id); + try { + this.context.resourceManager.getStringSync($r('app.string.test').id); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getStringSync9+ @@ -1459,6 +1911,14 @@ getStringSync(resource: Resource): string | ------ | ---------------- | | string | resource对象对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -1466,7 +1926,11 @@ getStringSync(resource: Resource): string moduleName: "entry", id: $r('app.string.test').id }; - this.context.resourceManager.getStringSync(resource); + try { + this.context.resourceManager.getStringSync(resource); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getStringByNameSync9+ @@ -1487,9 +1951,21 @@ getStringByNameSync(resName: string): string | ------ | ---------- | | string | 资源名称对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getStringByNameSync("test"); + try { + this.context.resourceManager.getStringByNameSync("test"); + } catch (error) { + console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getBoolean9+ @@ -1510,9 +1986,21 @@ getBoolean(resId: number): boolean | ------- | ------------ | | boolean | 资源ID值对应的布尔结果 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id); + try { + this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id); + } catch (error) { + console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getBoolean9+ @@ -1532,6 +2020,14 @@ getBoolean(resource: Resource): boolean | ------- | ----------------- | | boolean | resource对象对应的布尔结果 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -1539,7 +2035,11 @@ getBoolean(resource: Resource): boolean moduleName: "entry", id: $r('app.boolean.boolean_test').id }; - this.context.resourceManager.getBoolean(resource); + try { + this.context.resourceManager.getBoolean(resource); + } catch (error) { + console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getBooleanByName9+ @@ -1560,9 +2060,21 @@ getBooleanByName(resName: string): boolean | ------- | ----------- | | boolean | 资源名称对应的布尔结果 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getBooleanByName("boolean_test"); + try { + this.context.resourceManager.getBooleanByName("boolean_test"); + } catch (error) { + console.error(`getBooleanByName failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getNumber9+ @@ -1583,10 +2095,27 @@ getNumber(resId: number): number | ------ | ---------- | | number | 资源ID值对应的数值 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts - this.context.resourceManager.getNumber($r('app.integer.integer_test').id); - this.context.resourceManager.getNumber($r('app.float.float_test').id); + try { + this.context.resourceManager.getNumber($r('app.integer.integer_test').id); + } catch (error) { + console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) + } + + try { + this.context.resourceManager.getNumber($r('app.float.float_test').id); + } catch (error) { + console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getNumber9+ @@ -1607,6 +2136,14 @@ getNumber(resource: Resource): number | ------ | --------------- | | number | resource对象对应的数值 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | The resId invalid. | +| 9001002 | The resource not found by resId. | +| 9001006 | The resource re-ref too much. | + **示例:** ```ts let resource = { @@ -1614,7 +2151,11 @@ getNumber(resource: Resource): number moduleName: "entry", id: $r('app.integer.integer_test').id }; - this.context.resourceManager.getNumber(resource); + try { + this.context.resourceManager.getNumber(resource); + } catch (error) { + console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getNumberByName9+ @@ -1635,8 +2176,464 @@ getNumberByName(resName: string): number | ------ | --------- | | number | 资源名称对应的数值 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | The resName invalid. | +| 9001004 | The resource not found by resName. | +| 9001006 | The resource re-ref too much. | + +**示例:** + ```ts + try { + this.context.resourceManager.getNumberByName("integer_test"); + } catch (error) { + console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`) + } + + try { + this.context.resourceManager.getNumberByName("float_test"); + } catch (error) { + console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + + +### getString(deprecated) + +getString(resId: number, callback: AsyncCallback<string>): void + +用户获取指定资源ID对应的字符串,使用callback形式返回字符串。 + +从API version 9开始不再维护,建议使用[getStringValue](#getstringvalue9)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | 是 | 资源ID值 | +| callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的字符串 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getString($r('app.string.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + }); + ``` + + +### getString(deprecated) + +getString(resId: number): Promise<string> + +用户获取指定资源ID对应的字符串,使用Promise形式返回字符串。 + +从API version 9开始不再维护,建议使用[getStringValue](#getstringvalue9-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | + +**返回值:** +| 类型 | 说明 | +| --------------------- | ----------- | +| Promise<string> | 资源ID值对应的字符串 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getString($r('app.string.test').id).then(value => { + let str = value; + }).catch(error => { + console.log("getstring promise error is " + error); + }); + }); + ``` + + +### getStringArray(deprecated) + +getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void + +用户获取指定资源ID对应的字符串数组,使用callback形式返回字符串数组。 + +从API version 9开始不再维护,建议使用[getStringArrayValue](#getstringarrayvalue9)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | 是 | 资源ID值 | +| callback | AsyncCallback<Array<string>> | 是 | 异步回调,用于返回获取的字符串数组 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray($r('app.strarray.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + }); + ``` + + +### getStringArray(deprecated) + +getStringArray(resId: number): Promise<Array<string>> + +用户获取指定资源ID对应的字符串数组,使用Promise形式返回字符串数组。 + +从API version 9开始不再维护,建议使用[getStringArrayValue](#getstringarrayvalue9-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | + +**返回值:** +| 类型 | 说明 | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | 资源ID值对应的字符串数组 | + **示例:** ```ts - this.context.resourceManager.getNumberByName("integer_test"); - this.context.resourceManager.getNumberByName("float_test"); + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray($r('app.strarray.test').id).then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArray promise error is " + error); + }); + }); + ``` + + +### getMedia(deprecated) + +getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void + +用户获取指定资源ID对应的媒体文件内容,使用callback形式返回字节数组。 + +从API version 9开始不再维护,建议使用[getMediaContent](#getmediacontent)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | 是 | 资源ID值 | +| callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的媒体文件内容 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + }); + ``` + + +### getMedia(deprecated) + +getMedia(resId: number): Promise<Uint8Array> + +用户获取指定资源ID对应的媒体文件内容,使用Promise形式返回字节数组。 + +从API version 9开始不再维护,建议使用[getMediaContent](#getmediacontent-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | + +**返回值:** +| 类型 | 说明 | +| ------------------------- | -------------- | +| Promise<Uint8Array> | 资源ID值对应的媒体文件内容 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia($r('app.media.test').id).then(value => { + let media = value; + }).catch(error => { + console.log("getMedia promise error is " + error); + }); + }); + ``` + + +### getMediaBase64(deprecated) + +getMediaBase64(resId: number, callback: AsyncCallback<string>): void + +用户获取指定资源ID对应的图片资源Base64编码,使用callback形式返回字符串。 + +从API version 9开始不再维护,建议使用[getMediaContentBase64](#getmediacontentbase64)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | 是 | 资源ID值 | +| callback | AsyncCallback<string> | 是 | 异步回调,用于返回获取的图片资源Base64编码 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + }); + ``` + + +### getMediaBase64(deprecated) + +getMediaBase64(resId: number): Promise<string> + +用户获取指定资源ID对应的图片资源Base64编码,使用Promise形式返回字符串。 + +从API version 9开始不再维护,建议使用[getMediaContentBase64](#getmediacontentbase64-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | + +**返回值:** +| 类型 | 说明 | +| --------------------- | -------------------- | +| Promise<string> | 资源ID值对应的图片资源Base64编码 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64($r('app.media.test').id).then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64 promise error is " + error); + }); + }); + ``` + + +### getPluralString(deprecated) + +getPluralString(resId: number, num: number): Promise<string> + +根据指定数量获取对指定ID字符串表示的单复数字符串,使用Promise形式返回字符串。 + +从API version 9开始不再维护,建议使用[getPluralStringValue](#getpluralstringvalue)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | +| num | number | 是 | 数量值 | + +**返回值:** +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<string> | 根据提供的数量获取对应ID字符串表示的单复数字符串 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString($r("app.plural.test").id, 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralString promise error is " + error); + }); + }); + ``` + + +### getPluralString(deprecated) + +getPluralString(resId: number, num: number, callback: AsyncCallback<string>): void + +根据指定数量获取指定ID字符串表示的单复数字符串,使用callback形式返回字符串。 + +从API version 9开始不再维护,建议使用[getPluralStringValue](#getpluralstringvalue-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | 是 | 资源ID值 | +| num | number | 是 | 数量值 | +| callback | AsyncCallback<string> | 是 | 异步回调,返回根据指定数量获取指定ID字符串表示的单复数字符串 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + }); + ``` + + +### getRawFile(deprecated) + +getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void + +用户获取resources/rawfile目录下对应的rawfile文件内容,使用callback形式返回字节数组。 + +从API version 9开始不再维护,建议使用[getRawFileContent](#getrawfilecontent9)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | 是 | rawfile文件路径 | +| callback | AsyncCallback<Uint8Array> | 是 | 异步回调,用于返回获取的rawfile文件内容 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFile("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + } + }); + }); + ``` + + +### getRawFile(deprecated) + +getRawFile(path: string): Promise<Uint8Array> + +用户获取resources/rawfile目录下对应的rawfile文件内容,使用Promise形式返回字节数组。 + +从API version 9开始不再维护,建议使用[getRawFileContent](#getrawfilecontent9-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ----------- | +| path | string | 是 | rawfile文件路径 | + +**返回值:** +| 类型 | 说明 | +| ------------------------- | ----------- | +| Promise<Uint8Array> | rawfile文件内容 | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFile("test.xml").then(value => { + let rawFile = value; + }).catch(error => { + console.log("getRawFile promise error is " + error); + }); + }); + ``` + + +### getRawFileDescriptor(deprecated) + +getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor>): void + +用户获取resources/rawfile目录下对应rawfile文件的descriptor,使用callback形式返回。 + +从API version 9开始不再维护,建议使用[getRawFd](#getrawfd9)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| path | string | 是 | rawfile文件路径 | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFileDescriptor("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + } + }); + }); + ``` + +### getRawFileDescriptor(deprecated) + +getRawFileDescriptor(path: string): Promise<RawFileDescriptor> + +用户获取resources/rawfile目录下对应rawfile文件的descriptor,使用Promise形式返回。 + +从API version 9开始不再维护,建议使用[getRawFd](#getrawfd9-1)代替。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ----------- | +| path | string | 是 | rawfile文件路径 | + +**返回值:** +| 类型 | 说明 | +| ---------------------------------------- | ------------------- | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | rawfile文件descriptor | + +**示例:** + ```ts + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFileDescriptor("test.xml").then(value => { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + }).catch(error => { + console.log("getRawFileDescriptor promise error is " + error); + }); + }); ``` \ No newline at end of file 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-system-device.md b/zh-cn/application-dev/reference/apis/js-apis-system-device.md index dec8bf99b4096f9680bdc3027d47dc035d7c4e1c..041de24dcec98a54249d43b79335721e7f97d315 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-device.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-device.md @@ -1,19 +1,18 @@ # 设备信息 +本模块提供当前设备的信息。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 从API Version 6开始,该接口不再维护,推荐使用新接口[`@ohos.deviceInfo`](js-apis-device-info.md)进行设备信息查询。 > > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 - ``` import device from '@system.device'; ``` - ## device.getInfo getInfo(Object): void @@ -23,7 +22,7 @@ getInfo(Object): void > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 在首页的onShow生命周期之前不建议调用device.getInfo接口。 -**系统能力:** SystemCapability.Startup.SysInfo +**系统能力:** SystemCapability.Startup.SystemInfo **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md index 0e824de04cfa4dd1de206838d519ace19d934ce2..1e6f73189bdcdcd1486b869cd1788513e5a9cddc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uitest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -4,10 +4,13 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 该模块提供以下功能: -- [By](#by):提供控件特征描述能力,用于控件筛选匹配查找。 -- [UiComponent](#uicomponent):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。 -- [UiDriver](#uidriver):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能能力。 -- [UiWINDOW9+](#uiwindow9):入口类,提供窗口属性获取,窗口拖动、调整窗口大小等能能力。 +- [On9+](#on9):提供控件特征描述能力,用于控件筛选匹配查找。 +- [Component9+](#component9):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。 +- [Driver9+](#driver9):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能能力。 +- [UiWindow9+](#uiwindow9):入口类,提供窗口属性获取,窗口拖动、调整窗口大小等能能力。 +- [By](#by):提供控件特征描述能力,用于控件筛选匹配查找。从API version9开始不再维护,建议使用[[On9+](#on9)](#driver9)。 +- [UiComponent](#uicomponent):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。从API version9开始不再维护,建议使用[Component9+](#component9)。 +- [UiDriver](#uidriver):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能能力。从API version9开始不再维护,建议使用[Driver9+](#driver9)。 >**说明:** > @@ -16,79 +19,52 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 ## 导入模块 -``` -import {UiDriver, BY, MatchPattern, ResizeDirection, WindowMode, DisplayRotation, PointerMatrix} from '@ohos.uitest' -``` - -## By - -UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
-By提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[By.isBefore](#isbefore)和[By.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。 - ```js -BY.text('123').type('button') +import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest' ``` -### text - -text(txt: string, pattern?: MatchPattern): By - -指定目标控件文本属性,支持多种匹配模式,返回By对象自身。 - -**系统能力**:SystemCapability.Test.UiTest - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------ | ---- | --------------------------------------------------- | -| txt | string | 是 | 指定控件文本,用于匹配目标控件文本。 | -| pattern | MatchPattern | 否 | 指定的文本匹配模式,默认为[EQUALS](#matchpattern)。 | - -**返回值:** - -| 类型 | 说明 | -| --------- | ---------------------------------- | -| [By](#by) | 返回指定目标控件文本属性的By对象。 | +## On9+ -**示例:** +UiTest框架在API9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
+On提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[ON.isBefore](#isbefore)和[ON.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
On类提供的所有API均为同步接口,建议使用者通过静态构造器ON来链式创建On对象。 ```js -let by = BY.text('123') //使用静态构造器BY创建by对象,指定目标控件的text属性。 +ON.text('123').type('button') ``` +### text9+ -### key - -key(key: string): By +text(txt: string, pattern?: MatchPattern): On -指定目标控件key值属性,返回By对象自身。 +指定目标控件文本属性,支持多种匹配模式,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ----------------- | -| key | string | 是 | 指定控件的Key值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------- | ---- | --------------------------------------------------- | +| txt | string | 是 | 指定控件文本,用于匹配目标控件文本。 | +| pattern | [MatchPattern](#matchpattern) | 否 | 指定的文本匹配模式,默认为[EQUALS](#matchpattern)。 | **返回值:** -| 类型 | 说明 | -| --------- | ----------------------------------- | -| [By](#by) | 返回指定目标控件key值属性的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------- | +| [On](#on9) | 返回指定目标控件文本属性的On对象。 | **示例:** ```js -let by = BY.key('123') //使用静态构造器BY创建by对象,指定目标控件的key值属性。 +let on = ON.text('123') //使用静态构造器ON创建On对象,指定目标控件的text属性。 ``` -### id +### id9+ -id(id: number): By +id(id: string): On -指定目标控件id属性,返回By对象自身。 +指定目标控件id属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest @@ -96,26 +72,26 @@ id(id: number): By | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ---------------- | -| id | number | 是 | 指定控件的id值。 | +| id | string | 是 | 指定控件的id值。 | **返回值:** -| 类型 | 说明 | -| --------- | -------------------------------- | -| [By](#by) | 返回指定目标控件id属性的By对象。 | +| 类型 | 说明 | +| ---------- | -------------------------------- | +| [On](#on9) | 返回指定目标控件id属性的On对象。 | **示例:** ```js -let by = BY.id(123) //使用静态构造器BY创建by对象,指定目标控件的id属性。 +let on = ON.id(123) //使用静态构造器ON创建On对象,指定目标控件的id属性。 ``` -### type +### type9+ -type(tp: string): By +type(tp: string): On -指定目标控件的控件类型属性,返回By对象自身。 +指定目标控件的控件类型属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest @@ -127,326 +103,311 @@ type(tp: string): By **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的控件类型属性的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------- | +| [On](#on9) | 返回指定目标控件的控件类型属性的On对象。 | **示例:** ```js -let by = BY.type('button') //使用静态构造器BY创建by对象,指定目标控件的控件类型属性。 +let on = ON.type('button') //使用静态构造器ON创建On对象,指定目标控件的控件类型属性。 ``` -### clickable +### clickable9+ -clickable(b?: boolean): By +clickable(b?: boolean): On -指定目标控件的可点击状态属性,返回By对象自身。 +指定目标控件的可点击状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | -------------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | | b | boolean | 否 | 指定控件可点击状态,true:可点击,false:不可点击。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的可点击状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ------------------------------------------ | +| [On](#on9) | 返回指定目标控件的可点击状态属性的On对象。 | **示例:** ```js -let by = BY.clickable(true) //使用静态构造器BY创建by对象,指定目标控件的可点击状态属性。 +let on = ON.clickable(true) //使用静态构造器ON创建On对象,指定目标控件的可点击状态属性。 ``` ### longClickable9+ -longClickable(b?: boolean): By +longClickable(b?: boolean): On -指定目标控件的可长按点击状态属性,返回By对象自身。 +指定目标控件的可长按点击状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | | b | boolean | 否 | 指定控件可长按点击状态,true:可长按点击,false:不可长按点击。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------------- | -| [By](#by) | 返回指定目标控件的可长按点击状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------------- | +| [On](#on9) | 返回指定目标控件的可长按点击状态属性的On对象。 | **示例:** ```js -let by = BY.longClickable(true) //使用静态构造器BY创建by对象,指定目标控件的可长按点击状态属性。 +let on = ON.longClickable(true) //使用静态构造器ON创建On对象,指定目标控件的可长按点击状态属性。 ``` -### scrollable +### scrollable9+ -scrollable(b?: boolean): By +scrollable(b?: boolean): On -指定目标控件的可滑动状态属性,返回By对象自身。 +指定目标控件的可滑动状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ---------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ----------------------------------------------------------- | | b | boolean | 否 | 控件可滑动状态,true:可滑动,false:不可滑动。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的可滑动状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ------------------------------------------ | +| [On](#on9) | 返回指定目标控件的可滑动状态属性的On对象。 | **示例:** ```js -let by = BY.scrollable(true) //使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性。 +let on = ON.scrollable(true) //使用静态构造器ON创建On对象,指定目标控件的可滑动状态属性。 ``` -### enabled +### enabled9+ -enabled(b?: boolean): By +enabled(b?: boolean): On -指定目标控件的使能状态属性,返回By对象自身。 +指定目标控件的使能状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | --------------------------------------------------------- | | b | boolean | 否 | 指定控件使能状态,true:使能,false:未使能。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的使能状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------- | +| [On](#on9) | 返回指定目标控件的使能状态属性的On对象。 | **示例:** ```js -let by = BY.enabled(true) //使用静态构造器BY创建by对象,指定目标控件的使能状态属性。 +let on = ON.enabled(true) //使用静态构造器ON创建On对象,指定目标控件的使能状态属性。 ``` -### focused +### focused9+ -focused(b?: boolean): By +focused(b?: boolean): On -指定目标控件的获焦状态属性,返回By对象自身。 +指定目标控件的获焦状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | -------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ----------------------------------------------------- | | b | boolean | 否 | 控件获焦状态,true:获焦,false:未获焦。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的获焦状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------- | +| [On](#on9) | 返回指定目标控件的获焦状态属性的On对象。 | **示例:** ```js -let by = BY.focused(true) //使用静态构造器BY创建by对象,指定目标控件的获焦状态属性。 +let on = ON.focused(true) //使用静态构造器ON创建On对象,指定目标控件的获焦状态属性。 ``` -### selected +### selected9+ -selected(b?: boolean): By +selected(b?: boolean): On -指定目标控件的被选中状态属性,返回By对象自身。 +指定目标控件的被选中状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | -------------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | | b | boolean | 否 | 指定控件被选中状态,true:被选中,false:未被选中。默认为true。 | **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的被选中状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ------------------------------------------ | +| [On](#on9) | 返回指定目标控件的被选中状态属性的On对象。 | **示例:** ```js -let by = BY.selected(true) //使用静态构造器BY创建by对象,指定目标控件的被选中状态属性。 +let on = ON.selected(true) //使用静态构造器ON创建On对象,指定目标控件的被选中状态属性。 ``` ### checked9+ -checked(b?: boolean): By +checked(b?: boolean): On -指定目标控件的被勾选状态属性,返回By对象自身。 +指定目标控件的被勾选状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | --------------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | | b | boolean | 否 | 指定控件被勾选状态,true:被勾选,false:未被勾选。默认为false。 | **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的被勾选状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | ------------------------------------------ | +| [On](#on9) | 返回指定目标控件的被勾选状态属性的On对象。 | **示例:** ```js -let by = BY.checked(true) //使用静态构造器BY创建by对象,指定目标控件的被勾选状态属性 +let on = ON.checked(true) //使用静态构造器ON创建On对象,指定目标控件的被勾选状态属性 ``` ### checkable9+ -checkable(b?: boolean): By +checkable(b?: boolean): On -指定目标控件能否被勾选状态属性,返回By对象自身。 +指定目标控件能否被勾选状态属性,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ------------------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | | b | boolean | 否 | 指定控件能否被勾选状态,true:能被勾选,false:不能被勾选。默认为false。 | **返回值:** -| 类型 | 说明 | -| --------- | -------------------------------------------- | -| [By](#by) | 返回指定目标控件能否被勾选状态属性的By对象。 | +| 类型 | 说明 | +| ---------- | -------------------------------------------- | +| [On](#on9) | 返回指定目标控件能否被勾选状态属性的On对象。 | **示例:** ```js -let by = BY.checkable(true) //使用静态构造器BY创建by对象,指定目标控件的能否被勾选状态属性。 +let on = ON.checkable(true) //使用静态构造器ON创建On对象,指定目标控件的能否被勾选状态属性。 ``` -### isBefore +### isBefore9+ -isBefore(by: By): By +isBefore(on: On): On -指定目标控件位于给出的特征属性控件之前,返回By对象自身。 +指定目标控件位于给出的特征属性控件之前,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ---------------- | -| by | [By](#by) | 是 | 特征控件的属性。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 特征控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------------------- | -| [By](#by) | 返回指定目标控件位于给出的特征属性控件之前的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------------------- | +| [On](#on9) | 返回指定目标控件位于给出的特征属性控件之前的On对象。 | **示例:** ```js -let by = BY.isBefore(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前。 +let on = ON.isBefore(ON.text('123')) //使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之前。 ``` -### isAfter +### isAfter9+ -isAfter(by: By): By +isAfter(on: On): On -指定目标控件位于给出的特征属性控件之后,返回By对象自身。 +指定目标控件位于给出的特征属性控件之后,返回On对象自身。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ---------------- | -| by | [By](#by) | 是 | 特征控件的属性。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 特征控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------------------- | -| [By](#by) | 返回指定目标控件位于给出的特征属性控件之后的By对象。 | +| 类型 | 说明 | +| ---------- | ---------------------------------------------------- | +| [On](#on9) | 返回指定目标控件位于给出的特征属性控件之后的On对象。 | **示例:** ```js -let by = BY.isAfter(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后。 +let on = ON.isAfter(ON.text('123')) //使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之后。 ``` -## UiComponent +## Component9+ -UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 +UiTest框架在API9中,Component类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 -### Point9+ - -坐标点信息。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ---- | -------- | ---- | ---- | ---------------- | -| X | number | 是 | 否 | 坐标点的横坐标。 | -| Y | number | 是 | 否 | 坐标点的纵坐标。 | +### click9+ -### Rect9+ +click(): Promise\ -控件的边框信息。 +控件对象进行点击操作。 **系统能力**:SystemCapability.Test.UiTest -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ------- | -------- | ---- | ---- | ------------------------- | -| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | -| topY | number | 是 | 否 | 控件边框的左上角的Y坐标。 | -| rightX | number | 是 | 否 | 控件边框的右下角的X坐标。 | -| bottomY | number | 是 | 否 | 控件边框的右下角的Y坐标。 | - -### UiComponent.click - -click(): Promise\ +**错误码:** -控件对象进行点击操作。 +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -**系统能力**:SystemCapability.Test.UiTest +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) await button.click() } ``` -### doubleClick +### doubleClick9+ doubleClick(): Promise\ @@ -454,17 +415,26 @@ doubleClick(): Promise\ **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) await button.doubleClick() } ``` -### longClick +### longClick9+ longClick(): Promise\ @@ -472,19 +442,28 @@ longClick(): Promise\ **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) await button.longClick() } ``` -### getId +### getId9+ -getId(): Promise\ +getId(): Promise\ 获取控件对象的id值。 @@ -494,43 +473,28 @@ getId(): Promise\ | 类型 | 说明 | | ---------------- | ------------------------------- | -| Promise\ | 以Promise形式返回的控件的id值。 | - -**示例:** - -```js -async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let num = await button.getId() -} -``` - -### getKey - -getKey(): Promise\ - -获取控件对象的key值。 +| Promise\ | 以Promise形式返回的控件的id值。 | -**系统能力**:SystemCapability.Test.UiTest +**错误码:** -**返回值:** +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -| 类型 | 说明 | -| ---------------- | ------------------------------ | -| Promise\ | 以Promise形式返回控件的key值。 | +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let str_key = await button.getKey() + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) + let num = await button.getId() } ``` -### getText +### getText9+ getText(): Promise\ @@ -544,17 +508,26 @@ getText(): Promise\ | ---------------- | --------------------------------- | | Promise\ | 以Promise形式返回控件的文本信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) let text = await button.getText() } ``` -### getType +### getType9+ getType(): Promise\ @@ -568,12 +541,21 @@ getType(): Promise\ | ---------------- | ----------------------------- | | Promise\ | 以Promise形式返回控件的类型。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) let type = await button.getType() } ``` @@ -592,12 +574,21 @@ getBounds(): Promise\ | ------------------------ | ------------------------------------- | | Promise\<[Rect](#rect9)> | 以Promise形式返回控件对象的边框信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) let rect = await button.getBounds() } ``` @@ -616,17 +607,26 @@ getBoundsCenter(): Promise\ | -------------------------- | --------------------------------------- | | Promise\<[Point](#point9)> | 以Promise形式返回控件对象的中心点信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) let point = await button.getBoundsCenter() } ``` -### isClickable +### isClickable9+ isClickable(): Promise\ @@ -636,16 +636,25 @@ isClickable(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象可点击状态,true:可点击,false:不可点击。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) if(await button.isClickable()) { console.info('This button can be Clicked') } @@ -665,16 +674,25 @@ isLongClickable(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象能否长按点击状态,true:可长按点击,false:不可长按点击。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) if(await button.isLongClickable()) { console.info('This button can longClick') } @@ -694,16 +712,25 @@ isChecked(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象被勾选状态,true:被勾选,false:未被勾选。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let checkBox = await driver.findComponent(BY.type('Checkbox')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('Checkbox')) if(await checkBox.isChecked) { console.info('This checkBox is checked') } @@ -723,16 +750,25 @@ isCheckable(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------------- | +| 错误码ID | 错误码信息 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象能否被勾选的属性,true:可被勾选,false:不可被勾选。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 类型 | 说明 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let checkBox = await driver.findComponent(BY.type('Checkbox')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('Checkbox')) if(await checkBox.isCheckable) { console.info('This checkBox is checkable') } @@ -742,7 +778,7 @@ async function demo() { } ``` -### isScrollable +### isScrollable9+ isScrollable(): Promise\ @@ -752,16 +788,25 @@ isScrollable(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象可滑动状态,true:可滑动,false:不可滑动。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let driver = Driver.create() + let button = await driver.findComponent(ON.scrollable(true)) if(await scrollBar.isScrollable()) { console.info('This scrollBar can be operated') } @@ -772,7 +817,7 @@ async function demo() { ``` -### isEnabled +### isEnabled9+ isEnabled(): Promise\ @@ -782,16 +827,25 @@ isEnabled(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------- | +| 类型 | 说明 | +| ----------------- | ---------------------------------------------------------- | | Promise\ | 以Promise形式返回控件使能状态,true:使能,false:未使能。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) if(await button.isEnabled()) { console.info('This button can be operated') } @@ -802,7 +856,7 @@ async function demo() { ``` -### isFocused +### isFocused9+ isFocused(): Promise\ @@ -812,16 +866,25 @@ isFocused(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回控件对象是否获焦,true:获焦,false:未获焦。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) if(await button.isFocused()) { console.info('This button is focused') } @@ -831,7 +894,7 @@ async function demo() { } ``` -### isSelected +### isSelected9+ isSelected(): Promise\ @@ -841,16 +904,25 @@ isSelected(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | -------------------- | +| 类型 | 说明 | +| ----------------- | ----------------------------------------------------- | | Promise\ | 控件对象被选中的状态,true:被选中,false:未被选中。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) if(await button.isSelected()) { console.info('This button is selected') } @@ -860,7 +932,7 @@ async function demo() { } ``` -### inputText +### inputText9+ inputText(text: string): Promise\ @@ -874,12 +946,21 @@ inputText(text: string): Promise\ | ------ | ------ | ---- | ---------------- | | text | string | 是 | 输入的文本信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let text = await driver.findComponent(BY.text('hello world')) + let driver = Driver.create() + let button = await driver.findComponent(ON.text('hello world')) await text.inputText('123') } ``` @@ -892,19 +973,26 @@ clearText(): Promise\ **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let text = await driver.findComponent(BY.text('hello world')) + let driver = Driver.create() + let button = await driver.findComponent(ON.text('hello world')) await text.clearText() } ``` -### scrollSearch +### scrollSearch9+ -scrollSearch(by: By): Promise\ +scrollSearch(on: ON): Promise\ 在控件上滑动查找目标控件(适用于List等支持滑动的控件)。 @@ -912,23 +1000,32 @@ scrollSearch(by: By): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ------------------------------------- | -| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的目标控件对象。 | +| 类型 | 说明 | +| ---------------------------------- | ------------------------------------- | +| Promise\<[Component](#component9)> | 以Promise形式返回找到的目标控件对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) - let button = await scrollBar.scrollSearch(BY.text('next page')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('Scroll')) + let button = await scrollBar.scrollSearch(ON.text('next page')) } ``` @@ -944,14 +1041,23 @@ scrollToTop(speed?: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | -| speed | number | 否 | 滑动速率,范围:200-3000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 否 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('Scroll')) await scrollBar.scrollToTop() } ``` @@ -968,21 +1074,30 @@ scrollToBottom(speed?: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | -| speed | number | 否 | 滑动速率,范围:200-3000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 否 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('Scroll')) await scrollBar.scrollToBottom() } ``` ### dragTo9+ -dragTo(target: UiComponent): Promise\ +dragTo(target: Component): Promise\ 将控件拖拽至目标控件处。 @@ -990,17 +1105,26 @@ dragTo(target: UiComponent): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------------------------- | ---- | ---------- | -| target | [UiComponent](#uicomponent) | 是 | 目标控件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | ---------- | +| target | [Component](#component9) | 是 | 目标控件。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let text = await driver.findComponent(BY.text('hello world')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('button')) + let text = await driver.findComponent(ON.text('hello world')) await button.dragTo(text) } ``` @@ -1019,12 +1143,21 @@ pinchOut(scale: number): Promise\ | ------ | ------ | ---- | ---------------- | | scale | number | 是 | 指定放大的比例。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let image = await driver.findComponent(BY.type('image')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('image')) await image.pinchOut(1.5) } ``` @@ -1043,121 +1176,162 @@ pinchIn(scale: number): Promise\ | ------ | ------ | ---- | ---------------- | | scale | number | 是 | 指定缩小的比例。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() - let image = await driver.findComponent(BY.type('image')) + let driver = Driver.create() + let button = await driver.findComponent(ON.type('image')) await image.pinchIn(0.5) } ``` -## UiDriver +## Driver9+ -UiDriver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 -该类提供的方法除UiDriver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 +UiTest框架在API9中,Driver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 +该类提供的方法除Driver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 -### create +### create9+ -static create(): UiDriver +static create(): Driver -静态方法,构造一个UiDriver对象,并返回该对象。 +静态方法,构造一个Driver对象,并返回该对象。 **系统能力**:SystemCapability.Test.UiTest **返回值:** -| 类型 | 说明 | -| -------- | ------------------------ | -| UiDriver | 返回构造的UiDriver对象。 | +| 错误码ID | 错误码信息 | +| -------- | ---------------------- | +| Driver | 返回构造的Driver对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 类型 | 说明 | +| -------- | ------------------ | +| 17000001 | Initialize failed. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() } ``` -### delayMs +### delayMs9+ delayMs(duration: number): Promise\ -UiDriver对象在给定的时间内延时。 +Driver对象在给定的时间内延时。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------ | -| duration | number | 是 | 给定的时间。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------------------- | +| duration | number | 是 | 给定的时间,单位:ms。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.delayMs(1000) } ``` -### findComponent +### findComponent9+ -findComponent(by: By): Promise\ +findComponent(on: On): Promise\ -在UiDriver对象中,根据给出的目标控件属性要求查找目标控件。 +在Driver对象中,根据给出的目标控件属性要求查找目标控件。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | --------------------------------- | -| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的控件对象。 | +| 类型 | 说明 | +| ---------------------------------- | --------------------------------- | +| Promise\<[Component](#component9)> | 以Promise形式返回找到的控件对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.text('next page')) + let driver = Driver.create() + let button = await driver.findComponent(ON.text('next page')) } ``` -### findComponents +### findComponents9+ -findComponents(by: By): Promise\> +findComponents(on: On): Promise\> -在UiDriver对象中,根据给出的目标控件属性要求查找出所有匹配控件,以列表保存。 +在Driver对象中,根据给出的目标控件属性要求查找出所有匹配控件,以列表保存。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| --------------------------------------------- | --------------------------------------- | -| Promise\> | 以Promise形式返回找到的控件对象的列表。 | +| 类型 | 说明 | +| ------------------------------------------ | --------------------------------------- | +| Promise\> | 以Promise形式返回找到的控件对象的列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let buttonList = await driver.findComponents(BY.text('next page')) + let driver = Driver.create() + let buttonList = await driver.findComponents(ON.text('next page')) } ``` @@ -1181,90 +1355,123 @@ findWindow(filter: WindowFilter): Promise\ | -------------------------------- | ------------------------------------- | | Promise\<[UiWindow](#uiwindow9)> | 以Promise形式返回找到的目标窗口对象。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) } ``` ### waitForComponent9+ -waitForComponent(by: By, time: number): Promise\ +waitForComponent(on: On, time: number): Promise\ -在UiDriver对象中,在用户给定的时间内,持续查找满足控件属性要求的目标控件。 +在Driver对象中,在用户给定的时间内,持续查找满足控件属性要求的目标控件。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | -| time | number | 是 | 查找目标控件的持续时间。单位ms。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------------------- | +| On | [On](#on9) | 是 | 目标控件的属性要求。 | +| time | number | 是 | 查找目标控件的持续时间。单位ms。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | --------------------------------- | -| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的控件对象。 | +| 类型 | 说明 | +| --------------------------------- | --------------------------------- | +| Promise\<[Component](#component)> | 以Promise形式返回找到的控件对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.waitForComponent(BY.text('next page'),500) + let driver = Driver.create() + let button = await driver.waitForComponent(ON.text('next page'),500) } ``` -### assertComponentExist +### assertComponentExist9+ -assertComponentExist(by: By): Promise\ +assertComponentExist(on: On): Promise\ -断言API,用于断言当前界面存在满足给出的目标控件属性的控件; 如果控件不存在,该API将抛出JS异常,使当前测试用例失败。 +断言API,用于断言当前界面存在满足给出的目标控件属性的控件。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 目标控件的属性要求。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000003 | Component existence assertion failed. | **示例:** ```js async function demo() { - let driver = UiDriver.create() - await driver.assertComponentExist(BY.text('next page')) + let driver = Driver.create() + await driver.assertComponentExist(ON.text('next page')) } ``` -### pressBack +### pressBack9+ pressBack(): Promise\ -UiDriver对象进行点击BACK键的操作。 +Driver对象进行点击BACK键的操作。 **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.pressBack() } ``` -### triggerKey +### triggerKey9+ triggerKey(keyCode: number): Promise\ -UiDriver对象采取如下操作:通过key值找到对应键并点击。 +Driver对象采取如下操作:通过key值找到对应键并点击。 **系统能力**:SystemCapability.Test.UiTest @@ -1274,11 +1481,19 @@ UiDriver对象采取如下操作:通过key值找到对应键并点击。 | ------- | ------ | ---- | ------------- | | keyCode | number | 是 | 指定的key值。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.triggerKey(123) } ``` @@ -1287,33 +1502,41 @@ async function demo() { triggerCombineKeys(key0: number, key1: number, key2?: number): Promise\ -UiDriver对象通过给定的key值,找到对应组合键并点击。例如,Key值为(2072, 2019)时,UiDriver对象找到组合键并点击ctrl+c。 +Driver对象通过给定的key值,找到对应组合键并点击。例如,Key值为(2072, 2019)时,Driver对象找到组合键并点击ctrl+c。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | ------------------- | -| key0 | number | 是 | 指定的第一个key值。 | -| key1 | number | 是 | 指定的第二个key值。 | -| key2 | number | 否 | 指定的第三个key值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------- | +| key0 | number | 是 | 指定的第一个key值。 | +| key1 | number | 是 | 指定的第二个key值。 | +| key2 | number | 否 | 指定的第三个key值。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.triggerCombineKeys(2072, 2047, 2035) } ``` -### click +### click9+ click(x: number, y: number): Promise\ -UiDriver对象采取如下操作:在目标坐标点单击。 +Driver对象采取如下操作:在目标坐标点单击。 **系统能力**:SystemCapability.Test.UiTest @@ -1324,20 +1547,28 @@ UiDriver对象采取如下操作:在目标坐标点单击。 | x | number | 是 | 以number的形式传入目标点的横坐标信息。 | | y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.click(100,100) } ``` -### doubleClick +### doubleClick9+ doubleClick(x: number, y: number): Promise\ -UiDriver对象采取如下操作:在目标坐标点双击。 +Driver对象采取如下操作:在目标坐标点双击。 **系统能力**:SystemCapability.Test.UiTest @@ -1348,20 +1579,28 @@ UiDriver对象采取如下操作:在目标坐标点双击。 | x | number | 是 | 以number的形式传入目标点的横坐标信息。 | | y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.doubleClick(100,100) } ``` -### longClick +### longClick9+ longClick(x: number, y: number): Promise\ -UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 +Driver对象采取如下操作:在目标坐标点长按下。 **系统能力**:SystemCapability.Test.UiTest @@ -1372,11 +1611,19 @@ UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 | x | number | 是 | 以number的形式传入目标点的横坐标信息。 | | y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.longClick(100,100) } ``` @@ -1385,7 +1632,7 @@ async function demo() { swipe(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ -UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目的坐标点。 +Driver对象采取如下操作:从给出的起始坐标点滑向给出的目的坐标点。 **系统能力**:SystemCapability.Test.UiTest @@ -1397,13 +1644,21 @@ UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目 | starty | number | 是 | 以number的形式传入起始点的纵坐标信息。 | | endx | number | 是 | 以number的形式传入目的点的横坐标信息。 | | endy | number | 是 | 以number的形式传入目的点的纵坐标信息。 | -| speed | number | 否 | 滑动速率,范围:200-3000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 否 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.swipe(100,100,200,200,600) } ``` @@ -1412,7 +1667,7 @@ async function demo() { drag(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ -UiDriver对象采取如下操作:从给出的起始坐标点拖拽至给出的目的坐标点。 +Driver对象采取如下操作:从给出的起始坐标点拖拽至给出的目的坐标点。 **系统能力**:SystemCapability.Test.UiTest @@ -1424,22 +1679,30 @@ UiDriver对象采取如下操作:从给出的起始坐标点拖拽至给出的 | starty | number | 是 | 以number的形式传入起始点的纵坐标信息。 | | endx | number | 是 | 以number的形式传入目的点的横坐标信息。 | | endy | number | 是 | 以number的形式传入目的点的纵坐标信息。 | -| speed | number | 否 | 滑动速率,范围:200-3000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 否 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.drag(100,100,200,200,600) } ``` -### screenCap +### screenCap9+ screenCap(savePath: string): Promise\ -UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的图片至给出的保存路径中。 +Driver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的图片至给出的保存路径中。 **系统能力**:SystemCapability.Test.UiTest @@ -1451,15 +1714,23 @@ UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 **返回值:** -| 类型 | 说明 | -| -------------- | -------------------------------------- | +| 类型 | 说明 | +| ----------------- | -------------------------------------- | | Promise\ | 截图操作是否成功完成。成功完成为true。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.screenCap('/local/tmp/') } ``` @@ -1478,11 +1749,19 @@ setDisplayRotation(rotation: DisplayRotation): Promise\ | -------- | ------------------------------------ | ---- | ---------------- | | rotation | [DisplayRotation](#displayrotation9) | 是 | 设备的显示方向。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.setDisplayRotation(DisplayRotation.ROTATION_180) } ``` @@ -1501,11 +1780,19 @@ getDisplayRotation(): Promise\ | ---------------------------------------------- | --------------------------------------- | | Promise\<[DisplayRotation](#displayrotation9)> | 以Promise的形式返回当前设备的显示方向。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let rotation = await driver.getDisplayRotation() } ``` @@ -1520,15 +1807,23 @@ setDisplayRotationEnabled(enabled: boolean): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---- | ---- | -------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------- | | enabled | boolean | 是 | 能否旋转屏幕的标识,true:可以旋转,false:不可以旋转。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.setDisplayRotationEnabled(false) } ``` @@ -1547,11 +1842,19 @@ getDisplaySize(): Promise\ | -------------------------- | --------------------------------------- | | Promise\<[Point](#point9)> | 以Promise的形式返回当前设备的屏幕大小。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let size = await driver.getDisplaySize() } ``` @@ -1570,11 +1873,19 @@ getDisplayDensity(): Promise\ | -------------------------- | ------------------------------------------- | | Promise\<[Point](#point9)> | 以Promise的形式返回当前设备的屏幕的分辨率。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let density = await driver.getDisplayDensity() } ``` @@ -1587,11 +1898,19 @@ wakeUpDisplay(): Promise\ **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.wakeUpDisplay() } ``` @@ -1604,11 +1923,19 @@ pressHome(): Promise\ **系统能力**:SystemCapability.Test.UiTest +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.pressHome() } ``` @@ -1630,15 +1957,23 @@ waitForIdle(idleTime: number, timeout: number): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------------------------------- | +| 类型 | 说明 | +| ----------------- | --------------------------------------------------- | | Promise\ | 以Promise的形式返回当前界面的所有控件是否已经空闲。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let idled = await driver.waitForIdle(4000,5000) } ``` @@ -1656,15 +1991,23 @@ fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------- | ---- | ------------------------------------------------------------ | | from | [Point](#point9) | 是 | 手指接触屏幕的起始点坐标。 | -| to | [Point](#point9) | 是 | 手指离开屏幕时的坐标点。 | +| to | [Point](#point9) | 是 | 手指离开屏幕时的坐标点。 | | stepLen | number | 是 | 间隔距离,单位:像素点。 | -| speed | number | 是 | 滑动速率,范围:200-3000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 是 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() await driver.fling({X: 500, Y: 480},{X: 450, Y: 480},5,600) } ``` @@ -1682,14 +2025,22 @@ injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\ | 以Promise的形式返回植入操作是否成功完成。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + **示例:** ```js @@ -1705,23 +2056,73 @@ async function demo() { } ``` -## UiWindow9+ +## PointerMatrix9+ -UiTest中,UiWindow类代表了UI界面上的一个窗口,提供窗口属性获取,窗口拖动、调整窗口大小等API。 -该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 +表示存储多指操作中每根手指每一步动作的坐标点及其行为的二维数组。 + +### create9+ -### WindowFilter9+ +static create(fingers: number, steps: number): PointerMatrix -窗口的标志属性信息。 +静态方法,构造一个PointerMatrix对象,并返回该对象。 **系统能力**:SystemCapability.Test.UiTest -| 名称 | 参数类型 | 必填 | 可读 | 可写 | 描述 | -| ---------- | -------- | ---- | ---- | ---- | -------------------------- | -| bundleName | string | 否 | 是 | 否 | 窗口对应的包名。 | -| title | string | 否 | 是 | 否 | 窗口的标题。 | -| focused | boolean | 否 | 是 | 否 | 窗口是否获焦。 | -| actived | boolean | 否 | 是 | 否 | 窗口是否正与用户进行交互。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------------------------ | +| fingers | number | 是 | 多指操作中注入的手指数,取值范围:[1,10]。 | +| steps | number | 是 | 每根手指操作的步骤数,取值范围:[1,1000]。 | + +**返回值:** + +| 类型 | 说明 | +| -------------------------------- | ----------------------------- | +| [PointerMatrix](#pointermatrix9) | 返回构造的PointerMatrix对象。 | + +**示例:** + +```js +async function demo() { + let pointerMatrix = PointerMatrix.create(2,3) +} +``` + +### setPoint9+ + +setPoint(finger: number, step: number, point: Point): void + +设置PointerMatrix对象中指定手指和步骤对应动作的坐标点。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------- | ---- | ---------------- | +| finger | number | 是 | 手指的序号。 | +| step | number | 是 | 步骤的序号。 | +| point | [Point](#point9) | 是 | 该行为的坐标点。 | + +**示例:** + +```js +async function demo() { + let pointers = PointerMatrix.create(2,3) + pointers.setPoint(0,0,{X:230,Y:480}) + pointers.setPoint(0,1,{X:250,Y:380}) + pointers.setPoint(0,2,{X:270,Y:280}) + pointers.setPoint(1,0,{X:230,Y:680}) + pointers.setPoint(1,1,{X:240,Y:580}) + pointers.setPoint(1,2,{X:250,Y:480}) +} +``` + +## UiWindow9+ + +UiTest中,UiWindow类代表了UI界面上的一个窗口,提供窗口属性获取,窗口拖动、调整窗口大小等API。 +该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 ### getBundleName9+ @@ -1737,11 +2138,20 @@ getBundleName(): Promise\ | ---------------- | --------------------------------- | | Promise\ | 以Promise形式返回窗口的包名信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let name = await window.getBundleName() } @@ -1761,11 +2171,20 @@ getBounds(): Promise\ | ------------------------ | --------------------------------- | | Promise\<[Rect](#rect9)> | 以Promise形式返回窗口的边框信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let rect = await window.getBounds() } @@ -1785,11 +2204,20 @@ getTitle(): Promise\ | ---------------- | --------------------------------- | | Promise\ | 以Promise形式返回窗口的标题信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let rect = await window.getTitle() } @@ -1805,15 +2233,24 @@ getWindowMode(): Promise\ **返回值:** -| 类型 | 说明 | -| ------------------------------------------------ | ------------------------------------- | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------- | | Promise\<[WindowMode](#windowmode9)> | 以Promise形式返回窗口的窗口模式信息。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let mode = await window.getWindowMode() } @@ -1829,15 +2266,24 @@ isFocused(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回窗口对象是否获焦,true:获焦,false:未获焦。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let focused = await window.isFocused() } @@ -1853,15 +2299,24 @@ isActived(): Promise\ **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------------------------- | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回窗口对象是否为用户交互窗口,true:交互窗口,false:非交互窗口。 | +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) let focused = await window.isActived() } @@ -1869,23 +2324,26 @@ async function demo() { ### focus9+ -focus(): Promise\ +focus(): Promise\ 让窗口获焦。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.focus() } @@ -1893,7 +2351,7 @@ async function demo() { ### moveTo9+ -moveTo(x: number, y: number): Promise\ +moveTo(x: number, y: number): Promise\ 将窗口移动到目标点。适用于支持移动的窗口。 @@ -1906,17 +2364,21 @@ moveTo(x: number, y: number): Promise\ | x | number | 是 | 以number的形式传入目标点的横坐标信息。 | | y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | -**返回值:** +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.moveTo(100, 100) } @@ -1924,7 +2386,7 @@ async function demo() { ### resize9+ -resize(wide: number, height: number, direction: ResizeDirection): Promise\ +resize(wide: number, height: number, direction: ResizeDirection): Promise\ 根据传入的宽、高和调整方向来调整窗口的大小。适用于支持大小调整的窗口。 @@ -1932,23 +2394,27 @@ resize(wide: number, height: number, direction: ResizeDirection): Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.resize(100, 100, ResizeDirection.LEFT) } @@ -1956,23 +2422,27 @@ async function demo() { ### split9+ -split(): Promise\ +split(): Promise\ 将窗口模式切换成分屏模式。适用于支持切屏操作的窗口。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +| 类型 | 说明 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.split() } @@ -1980,23 +2450,27 @@ async function demo() { ### maximize9+ -maximize(): Promise\ +maximize(): Promise\ 将窗口最大化。适用于支持窗口最大化操作的窗口。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.maximize() } @@ -2004,23 +2478,27 @@ async function demo() { ### minimize9+ -minimize(): Promise\ +minimize(): Promise\ 将窗口最小化。适用于支持窗口最小化操作的窗口。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.minimize() } @@ -2028,23 +2506,27 @@ async function demo() { ### resume9+ -resume(): Promise\ +resume(): Promise\ 将窗口恢复到之前的窗口模式。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.resume() } @@ -2052,93 +2534,32 @@ async function demo() { ### close9+ -close(): Promise\ +close(): Promise\ 将窗口关闭。 **系统能力**:SystemCapability.Test.UiTest -**返回值:** +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 -| 类型 | 说明 | -| -------------- | ----------------------------------- | -| Promise\ | 以Promise形式返回操作是否成功完成,true:操作已完成,false:操作未完成。 | +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | **示例:** ```js async function demo() { - let driver = UiDriver.create() + let driver = Driver.create() let window = await driver.findWindow({actived: true}) await window.close() } ``` -## PointerMatrix9+ - -表示存储多指操作中每根手指每一步动作的坐标点及其行为的二维数组。 - -### create9+ - -static create(fingers: number, steps: number): PointerMatrix - -静态方法,构造一个PointerMatrix对象,并返回该对象。 - -**系统能力**:SystemCapability.Test.UiTest - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | ------------------------------------------ | -| fingers | number | 是 | 多指操作中注入的手指数,取值范围:[1,10]。 | -| steps | number | 是 | 每根手指操作的步骤数,取值范围:[1,1000]。 | - -**返回值:** - -| 类型 | 说明 | -| -------------------------------- | ----------------------------- | -| [PointerMatrix](#pointermatrix9) | 返回构造的PointerMatrix对象。 | - -**示例:** - -```js -async function demo() { - let pointerMatrix = PointerMatrix.create(2,3) -} -``` - -### setPoint9+ - -setPoint(finger: number, step: number, point: Point): void - -设置PointerMatrix对象中指定手指和步骤对应动作的坐标点。 - -**系统能力**:SystemCapability.Test.UiTest - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------- | ---- | ---------------- | -| finger | number | 是 | 手指的序号。 | -| step | number | 是 | 步骤的序号。 | -| point | [Point](#point9) | 是 | 该行为的坐标点。 | - -**示例:** - -```js -async function demo() { - let pointers = PointerMatrix.create(2,3) - pointers.setPoint(0,0,{X:230,Y:480}) - pointers.setPoint(0,1,{X:250,Y:380}) - pointers.setPoint(0,2,{X:270,Y:280}) - pointers.setPoint(1,0,{X:230,Y:680}) - pointers.setPoint(1,1,{X:240,Y:580}) - pointers.setPoint(1,2,{X:250,Y:480}) -} -``` - -### - ## MatchPattern 控件属性支持的匹配模式。 @@ -2169,6 +2590,30 @@ async function demo() { | RIGHT_UP | 右上方。 | | RIGHT_DOWN | 右下方。 | +## Point9+ + +坐标点信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ---- | -------- | ---- | ---- | ---------------- | +| X | number | 是 | 否 | 坐标点的横坐标。 | +| Y | number | 是 | 否 | 坐标点的纵坐标。 | + +## Rect9+ + +控件的边框信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ------- | -------- | ---- | ---- | ------------------------- | +| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | +| topY | number | 是 | 否 | 控件边框的左上角的Y坐标。 | +| rightX | number | 是 | 否 | 控件边框的右下角的X坐标。 | +| bottomY | number | 是 | 否 | 控件边框的右下角的Y坐标。 | + ## WindowMode9+ **系统能力**:SystemCapability.Test.UiTest @@ -2194,3 +2639,1052 @@ async function demo() { | ROTATION_90 | 设备显示器顺时针旋转90°,水平显示。 | | ROTATION_180 | 设备显示器顺时针旋转180°,逆向垂直显示。 | | ROTATION_270 | 设备显示器顺时针旋转270°,逆向水平显示。 | + +## WindowFilter9+ + +窗口的标志属性信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 必填 | 可读 | 可写 | 描述 | +| ---------- | -------- | ---- | ---- | ---- | -------------------------- | +| bundleName | string | 否 | 是 | 否 | 窗口对应的包名。 | +| title | string | 否 | 是 | 否 | 窗口的标题。 | +| focused | boolean | 否 | 是 | 否 | 窗口是否获焦。 | +| actived | boolean | 否 | 是 | 否 | 窗口是否正与用户进行交互。 | + +## By(deprecated) + +UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
+By提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[By.isBefore](#isbefore)和[By.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。 + +从API version9开始不再维护,建议使用[On9+](#on9)。 + +```js +BY.text('123').type('button') +``` + +### text(deprecated) + +text(txt: string, pattern?: MatchPattern): By + +指定目标控件文本属性,支持多种匹配模式,返回By对象自身。 + +从API version9开始不再维护,建议使用[text9+](#text9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------- | ---- | --------------------------------------------------- | +| txt | string | 是 | 指定控件文本,用于匹配目标控件文本。 | +| pattern | [MatchPattern](#matchpattern) | 否 | 指定的文本匹配模式,默认为[EQUALS](#matchpattern)。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------- | +| [By](#by) | 返回指定目标控件文本属性的By对象。 | + +**示例:** + +```js +let by = BY.text('123') //使用静态构造器BY创建by对象,指定目标控件的text属性。 +``` + + +### key(deprecated) + +key(key: string): By + +指定目标控件key值属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[id9+](#id9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------- | +| key | string | 是 | 指定控件的Key值。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ----------------------------------- | +| [By](#by) | 返回指定目标控件key值属性的By对象。 | + +**示例:** + +```js +let by = BY.key('123') //使用静态构造器BY创建by对象,指定目标控件的key值属性。 +``` + + +### id(deprecated) + +id(id: number): By + +指定目标控件id属性,返回By对象自身。 + +从API version9开始不再维护,被废弃。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| id | number | 是 | 指定控件的id值。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | -------------------------------- | +| [By](#by) | 返回指定目标控件id属性的By对象。 | + +**示例:** + +```js +let by = BY.id(123) //使用静态构造器BY创建by对象,指定目标控件的id属性。 +``` + + +### type(deprecated) + +type(tp: string): By + +指定目标控件的控件类型属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[type9+](#type9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------- | +| tp | string | 是 | 指定控件类型。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------------- | +| [By](#by) | 返回指定目标控件的控件类型属性的By对象。 | + +**示例:** + +```js +let by = BY.type('button') //使用静态构造器BY创建by对象,指定目标控件的控件类型属性。 +``` + + +### clickable(deprecated) + +clickable(b?: boolean): By + +指定目标控件的可点击状态属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[clickable9+](#clickable9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | 否 | 指定控件可点击状态,true:可点击,false:不可点击。默认为true。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ------------------------------------------ | +| [By](#by) | 返回指定目标控件的可点击状态属性的By对象。 | + +**示例:** + +```js +let by = BY.clickable(true) //使用静态构造器BY创建by对象,指定目标控件的可点击状态属性。 +``` + + +### scrollable(deprecated) + +scrollable(b?: boolean): By + +指定目标控件的可滑动状态属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[scrollable9+](#scrollable9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ----------------------------------------------------------- | +| b | boolean | 否 | 控件可滑动状态,true:可滑动,false:不可滑动。默认为true。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ------------------------------------------ | +| [By](#by) | 返回指定目标控件的可滑动状态属性的By对象。 | + +**示例:** + +```js +let by = BY.scrollable(true) //使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性。 +``` + +### enabled(deprecated) + +enabled(b?: boolean): By + +指定目标控件的使能状态属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[enabled9+](#enabled9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | --------------------------------------------------------- | +| b | boolean | 否 | 指定控件使能状态,true:使能,false:未使能。默认为true。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------------- | +| [By](#by) | 返回指定目标控件的使能状态属性的By对象。 | + +**示例:** + +```js +let by = BY.enabled(true) //使用静态构造器BY创建by对象,指定目标控件的使能状态属性。 +``` + +### focused(deprecated) + +focused(b?: boolean): By + +指定目标控件的获焦状态属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[focused9+](#focused9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ----------------------------------------------------- | +| b | boolean | 否 | 控件获焦状态,true:获焦,false:未获焦。默认为true。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------------- | +| [By](#by) | 返回指定目标控件的获焦状态属性的By对象。 | + +**示例:** + +```js +let by = BY.focused(true) //使用静态构造器BY创建by对象,指定目标控件的获焦状态属性。 +``` + +### selected(deprecated) + +selected(b?: boolean): By + +指定目标控件的被选中状态属性,返回By对象自身。 + +从API version9开始不再维护,建议使用[selected9+](#selected9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | 否 | 指定控件被选中状态,true:被选中,false:未被选中。默认为true。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ------------------------------------------ | +| [By](#by) | 返回指定目标控件的被选中状态属性的By对象。 | + +**示例:** + +```js +let by = BY.selected(true) //使用静态构造器BY创建by对象,指定目标控件的被选中状态属性。 +``` + +### isBefore(deprecated) + +isBefore(by: By): By + +指定目标控件位于给出的特征属性控件之前,返回By对象自身。 + +从API version9开始不再维护,建议使用[isBefore9+](#isbefore9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | ---------------- | +| by | [By](#by) | 是 | 特征控件的属性。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------------------------- | +| [By](#by) | 返回指定目标控件位于给出的特征属性控件之前的By对象。 | + +**示例:** + +```js +let by = BY.isBefore(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前。 +``` + +### isAfter(deprecated) + +isAfter(by: By): By + +指定目标控件位于给出的特征属性控件之后,返回By对象自身。 + +从API version9开始不再维护,建议使用[isAfter9+](#isafter9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | ---------------- | +| by | [By](#by) | 是 | 特征控件的属性。 | + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------------------------- | +| [By](#by) | 返回指定目标控件位于给出的特征属性控件之后的By对象。 | + +**示例:** + +```js +let by = BY.isAfter(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后。 +``` + +## UiComponent(deprecated) + +UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 +该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 + +从API version9开始不再维护,建议使用[Component9+](#component9)。 + +### click(deprecated) + +click(): Promise\ + +控件对象进行点击操作。 + +从API version9开始不再维护,建议使用[click9+](#click9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.click() +} +``` + +### doubleClick(deprecated) + +doubleClick(): Promise\ + +控件对象进行双击操作。 + +从API version9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.doubleClick() +} +``` + +### longClick(deprecated) + +longClick(): Promise\ + +控件对象进行长按操作。 + +从API version9开始不再维护,建议使用[longClick9+](#longclick9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.longClick() +} +``` + +### getId(deprecated) + +getId(): Promise\ + +获取控件对象的id值。 + +从API version9开始不再维护,建议使用[getId9+](#getid9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------- | +| Promise\ | 以Promise形式返回的控件的id值。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let num = await button.getId() +} +``` + +### getKey(deprecated) + +getKey(): Promise\ + +获取控件对象的key值。 + +从API version9开始不再维护,被废弃。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------ | +| Promise\ | 以Promise形式返回控件的key值。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let str_key = await button.getKey() +} +``` + +### getText(deprecated) + +getText(): Promise\ + +获取控件对象的文本信息。 + +从API version9开始不再维护,建议使用[getText9+](#gettext9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | --------------------------------- | +| Promise\ | 以Promise形式返回控件的文本信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let text = await button.getText() +} +``` + +### getType(deprecated) + +getType(): Promise\ + +获取控件对象的控件类型。 + +从API version9开始不再维护,建议使用[getType9+](#gettype9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------------- | +| Promise\ | 以Promise形式返回控件的类型。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let type = await button.getType() +} +``` + +### isClickable(deprecated) + +isClickable(): Promise\ + +获取控件对象可点击状态。 + +从API version9开始不再维护,建议使用[isClickable9+](#isclickable9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | 以Promise形式返回控件对象可点击状态,true:可点击,false:不可点击。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isClickable()) { + console.info('This button can be Clicked') + } + else{ + console.info('This button can not be Clicked') + } +} +``` + +### isScrollable(deprecated) + +isScrollable(): Promise\ + +获取控件对象可滑动状态。 + +从API version9开始不再维护,建议使用[isScrollable9+](#isscrollable9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | 以Promise形式返回控件对象可滑动状态,true:可滑动,false:不可滑动。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.scrollable(true)) + if(await scrollBar.isScrollable()) { + console.info('This scrollBar can be operated') + } + else{ + console.info('This scrollBar can not be operated') + } +} +``` + + +### isEnabled(deprecated) + +isEnabled(): Promise\ + +获取控件使能状态。 + +从API version9开始不再维护,建议使用[isEnabled9+](#isenabled9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ---------------------------------------------------------- | +| Promise\ | 以Promise形式返回控件使能状态,true:使能,false:未使能。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isEnabled()) { + console.info('This button can be operated') + } + else{ + console.info('This button can not be operated') + } +} + +``` + +### isFocused(deprecated) + +isFocused(): Promise\ + +判断控件对象是否获焦。 + +从API version9开始不再维护,建议使用[isFocused9+](#isfocused9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | 以Promise形式返回控件对象是否获焦,true:获焦,false:未获焦。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isFocused()) { + console.info('This button is focused') + } + else{ + console.info('This button is not focused') + } +} +``` + +### isSelected(deprecated) + +isSelected(): Promise\ + +获取控件对象被选中状态。 + +从API version9开始不再维护,建议使用[isSelected9+](#isselected9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ----------------------------------------------------- | +| Promise\ | 控件对象被选中的状态,true:被选中,false:未被选中。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isSelected()) { + console.info('This button is selected') + } + else{ + console.info('This button is not selected') + } +} +``` + +### inputText(deprecated) + +inputText(text: string): Promise\ + +向控件中输入文本(适用于文本框控件)。 + +从API version9开始不再维护,建议使用[inputText9+](#inputtext9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| text | string | 是 | 输入的文本信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let text = await driver.findComponent(BY.text('hello world')) + await text.inputText('123') +} +``` + +### scrollSearch(deprecated) + +scrollSearch(by: By): Promise\ + +在控件上滑动查找目标控件(适用于List等支持滑动的控件)。 + +从API version9开始不再维护,建议使用[scrollSearch9+](#scrollsearch9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | -------------------- | +| by | [By](#by) | 是 | 目标控件的属性要求。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------- | +| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的目标控件对象。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.type('Scroll')) + let button = await scrollBar.scrollSearch(BY.text('next page')) +} +``` + +## UiDriver(deprecated) + +UiDriver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 +该类提供的方法除UiDriver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 + +从API version9开始不再维护,建议使用[Driver9+](#driver9)。 + +### create(deprecated) + +static create(): UiDriver + +静态方法,构造一个UiDriver对象,并返回该对象。 + +从API version9开始不再维护,建议使用[create9+](#create9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------- | ------------------------ | +| UiDriver | 返回构造的UiDriver对象。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() +} +``` + +### delayMs(deprecated) + +delayMs(duration: number): Promise\ + +UiDriver对象在给定的时间内延时。 + +从API version9开始不再维护,建议使用[delayMs9+](#delayms9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------ | +| duration | number | 是 | 给定的时间。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.delayMs(1000) +} +``` + +### findComponent(deprecated) + +findComponent(by: By): Promise\ + +在UiDriver对象中,根据给出的目标控件属性要求查找目标控件。 + +从API version9开始不再维护,建议使用[findComponent9+](#findcomponent9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | -------------------- | +| by | [By](#by) | 是 | 目标控件的属性要求。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------- | --------------------------------- | +| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的控件对象。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.text('next page')) +} +``` + +### findComponents(deprecated) + +findComponents(by: By): Promise\> + +在UiDriver对象中,根据给出的目标控件属性要求查找出所有匹配控件,以列表保存。 + +从API version9开始不再维护,建议使用[findComponents9+](#findcomponents9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | -------------------- | +| by | [By](#by) | 是 | 目标控件的属性要求。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------------- | --------------------------------------- | +| Promise\> | 以Promise形式返回找到的控件对象的列表。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + let buttonList = await driver.findComponents(BY.text('next page')) +} +``` + +### assertComponentExist(deprecated) + +assertComponentExist(by: By): Promise\ + +断言API,用于断言当前界面存在满足给出的目标控件属性的控件; 如果控件不存在,该API将抛出JS异常,使当前测试用例失败。 + +从API version9开始不再维护,建议使用[assertComponentExist9+](#assertcomponentexist9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | -------------------- | +| by | [By](#by) | 是 | 目标控件的属性要求。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.assertComponentExist(BY.text('next page')) +} +``` + +### pressBack(deprecated) + +pressBack(): Promise\ + +UiDriver对象进行点击BACK键的操作。 + +从API version9开始不再维护,建议使用[pressBack9+](#pressback9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.pressBack() +} +``` + +### triggerKey(deprecated) + +triggerKey(keyCode: number): Promise\ + +UiDriver对象采取如下操作:通过key值找到对应键并点击。 + +从API version9开始不再维护,建议使用[triggerKey9+](#triggerkey9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------- | +| keyCode | number | 是 | 指定的key值。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.triggerKey(123) +} +``` + + +### click(deprecated) + +click(x: number, y: number): Promise\ + +UiDriver对象采取如下操作:在目标坐标点单击。 + +从API version9开始不再维护,建议使用[click9+](#click9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | 是 | 以number的形式传入目标点的横坐标信息。 | +| y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.click(100,100) +} +``` + +### doubleClick(deprecated) + +doubleClick(x: number, y: number): Promise\ + +UiDriver对象采取如下操作:在目标坐标点双击。 + +从API version9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | 是 | 以number的形式传入目标点的横坐标信息。 | +| y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.doubleClick(100,100) +} +``` + +### longClick(deprecated) + +longClick(x: number, y: number): Promise\ + +UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 + +从API version9开始不再维护,建议使用[longClick9+](#longclick9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | 是 | 以number的形式传入目标点的横坐标信息。 | +| y | number | 是 | 以number的形式传入目标点的纵坐标信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.longClick(100,100) +} +``` + +### swipe(deprecated) + +swipe(startx: number, starty: number, endx: number, endy: number): Promise\ + +UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目的坐标点。 + +从API version9开始不再维护,建议使用[swipe9+](#swipe9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | 是 | 以number的形式传入起始点的横坐标信息。 | +| starty | number | 是 | 以number的形式传入起始点的纵坐标信息。 | +| endx | number | 是 | 以number的形式传入目的点的横坐标信息。 | +| endy | number | 是 | 以number的形式传入目的点的纵坐标信息。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.swipe(100,100,200,200) +} +``` + +### screenCap(deprecated) + +screenCap(savePath: string): Promise\ + +UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的图片至给出的保存路径中。 + +从API version9开始不再维护,建议使用[screenCap9+](#screencap9)。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------------- | +| savePath | string | 是 | 文件保存路径。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------------- | +| Promise\ | 截图操作是否成功完成。成功完成为true。 | + +**示例:** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.screenCap('/local/tmp/') +} +``` 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 dd82886a62584ce50f6eb055377548bb45c68ed2..72fd78fd714cba79b0808191357914e3f33976fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @@ -57,7 +57,7 @@ startWork(work: WorkInfo): boolean mykey3: 1.5 } } - var res = workScheduler.startWork(workInfo); + let res = workScheduler.startWork(workInfo); console.info(`workschedulerLog res: ${res}`); ``` @@ -102,7 +102,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/apis/js-apis-zlib.md b/zh-cn/application-dev/reference/apis/js-apis-zlib.md index 4e86e1d8a387ab4e8d4d22d2a8b29d5daf019899..8138283e12eac6f85872a718f035bf00670afb64 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-zlib.md +++ b/zh-cn/application-dev/reference/apis/js-apis-zlib.md @@ -1,23 +1,24 @@ # Zip模块(JS端SDK接口) +本模块提供压缩解压缩文件的能力 + > **说明:** > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -## 使用限制 - -无。 ## 导入模块 ```javascript import zlib from '@ohos.zlib'; ``` -## zlib.zipFile -zipFile(inFile:string, outFile:string, options: Options): Promise<void> +## zlib.zipFile(deprecated) + zipFile(inFile:string, outFile:string, options: Options): Promise<void> 压缩接口(Promise形式)。 +> 从api9开始不再维护,建议使用[zlib.compressFile](#zlibcompressfile9) + **系统能力:** SystemCapability.BundleManager.Zlib **参数:** @@ -76,12 +77,14 @@ zlib.zipFile(inFile , outFile, options).then((data) => { }); ``` -## zlib.unzipFile +## zlib.unzipFile(deprecated) unzipFile(inFile:string, outFile:string, options: Options): Promise<void> 解压文件,解压完成返回执行结果(Promise形式)。 +> 从api9开始不再看护,建议使用[zlib.decompressFile](#zlibdecompressfile9) + **系统能力:** SystemCapability.BundleManager.Zlib **参数:** @@ -119,6 +122,193 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ``` +## zlib.compressFile9+ + +**function** compressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; + +压缩文件,压缩的结果通过callback返回。成功时返回null,失败时返回错误码。 + +**系统能力:** SystemCapability.BundleManager.Zlib + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压文件路径 | +| options | [Options](#options) | 是 | 压缩的配置参数 | +| AsyncCallback<**void**> | callback | 否 | 压缩时的回调函数 | + +**相关错误码** + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +**示例** + +```javascript +// 【压缩例子1】 +// 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 +import zlib from '@ohos.zlib' +var inFile = "/xxx/filename.xxx"; +var outFile = "/xxx/xxx.zip"; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.compressFile(inFile, outFile, options, (errData) => { + if (erData != null) { + console.log("errData is " + errData.errCode + " " + errData.message) + } + }) +} catch(errData => { + console.log("catch err " + errData.errCode + " " + errData.message) +}) +``` + +**function** compressFile(inFile:**string**, outFile:**string**, options: Options): Promise<**void**>; + +压缩文件,压缩的结果通过promise返回,成功时返回null,失败时返回错误码。 + +**系统能力:** SystemCapability.BundleManager.Zlib + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压文件路径 | +| options | [Options](#options) | 是 | 压缩的配置参数 | +| AsyncCallback<**void**> | callback | 否 | 压缩时的回调函数 | + +**相关错误码** + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +```javascript +// 【压缩例子2】 +// 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 +import zlib from '@ohos.zlib' +var inFile = "/xxx/filename.xxx"; +var outFile = "/xxx/xxx.zip"; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.compressFile(inFile, outFile, options).then(data => { + console.info("compressFile success") + }).catch(errData => { + console.info("catch err " + errData.errCode + " " + errData.message) + }) +} catch(errData => { + console.log("catch err " + errData.errCode + " " + errData.message) +}) +``` + + + +## zlib.decompressFile9+ + +**function** decompressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; + +解压文件,解压的结果通过callback返回,成功时返回null,失败时返回错误码。 + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定的待解压缩文件的文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压后的目录路径 | +| options | [Options](#options) | 是 | 解压的配置参数 | +| AsyncCallback<**void**> | callback | 否 | 解压是的回调函数 | + +**相关错误码** + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +**示例** + +```javascript +// 【解压缩例子1】 +// 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 +import zlib from '@ohos.zlib' +var inFile = "/xx/xxx.zip"; +var outFile = "/xxx"; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; +try { + zlib.decompressFile(inFile, outFile, options, (errData) => { + if (erData != null) { + console.log("errData is " + errData.errCode + " " + errData.message) + } + }) +} catch(errData => { + console.log("catch err " + errData.errCode + " " + errData.message) +}) +``` + +**function** decompressFile(inFile: **string**, outFile: **string**, options: Options): Promise<**void**>; + +解压文件,解压的结果通过promise返回,成功时返回null,失败时返回错误码。 + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定的待解压缩文件的文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压后的目录路径 | +| options | [Options](#options) | 是 | 解压时的配置参数 | + +**相关错误码** + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +```javascript +// 【解压缩例子2】 +// 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 +import zlib from '@ohos.zlib' +var inFile = "/xx/xxx.zip"; +var outFile = "/xxx"; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; +try { + zlib.compressFile(inFile, outFile, options).then(data => { + console.info("compressFile success") + }).catch(errData => { + console.info("catch err " + errData.errCode + " " + errData.message) + }) +} catch(errData => { + console.log("catch err " + errData.errCode + " " + errData.message) +}) +``` + ## Options **系统能力:** SystemCapability.BundleManager.Zlib 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-basic-components-datapanel.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index cc8d763c17ca1ba2368d6f3570b348272f2ef1f8..bcabffd14afc2f668cb5e6c15571fe572eb05ac3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -22,7 +22,7 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) | 参数名 | 参数类型 | 必填 | 参数描述 | | ----------------- | -------- | ----- | -------- | -| values | number[] | 是 | 数据值列表,最大支持9个数据。 | +| values | number[] | 是 | 数据值列表,最多包含9个数据,大于9个数据则取前9个数据。若数据值小于0则置为0。 | | max | number | 否 | - max大于0,表示数据的最大值。
- max小于等于0,max等于value数组各项的和,按比例显示。
默认值:100 | | type8+ | [DataPanelType](#datapaneltype枚举说明) | 否 | 数据面板的类型。
默认值:DataPanelType.Circle | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index 52bfcd5ba688f84db5e9dc57264545caa4453b89..a6031d9440bc49619853cc154bd01b5d5e13852f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -43,7 +43,7 @@ Gauge(options:{value: number, min?: number, max?: number}) | 名称 | 类型定义 | 描述 | | --------- | -------------------- | ------------------------------------------------------------ | -| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | 描述渐进色颜色断点类型,第一个参数为颜色值,第二个参数为0~1之间的比例值。 | +| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | 描述渐进色颜色断点类型,第一个参数为颜色值,若设置为非颜色类型,则置为黑色。第二个参数为颜色所占比重,若设置为负数或是非数值类型,则将比重置为0,该颜色不显示。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index e9155e11faaea76c751d01fbe8bffb0a5cee9c8b..d13a14c6835699a69d9f5e88211b0ef8d0e8bf11 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -1,6 +1,6 @@ # TextArea -可以输入多行文本并支持响应部分输入事件的组件。 +多行文本输入框组件,当输入的文本内容超过组件宽度时会自动换行显示。 > **说明:** > @@ -20,7 +20,7 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | 参数名 | 参数类型 | 必填 | 参数描述 | | ----------------------- | ---------------------------------------- | ---- | -------------- | -| placeholder | [ResourceStr](ts-types.md#resourcestr) | 否 | 无输入时的提示文本。 | +| placeholder | [ResourceStr](ts-types.md#resourcestr) | 否 | 设置无输入时的提示文本。 | | text | [ResourceStr](ts-types.md#resourcestr) | 否 | 设置输入框当前的文本内容。 | | controller8+ | [TextAreaController](#textareacontroller8) | 否 | 设置TextArea控制器。 | @@ -33,10 +33,10 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | ------------------------ | ---------------------------------------- | ---------------------------------------- | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | 设置placeholder文本颜色。 | | placeholderFont | [Font](ts-types.md#font) | 设置placeholder文本样式。 | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本水平对齐式。
默认值:TextAlign.Start | +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本在输入框中的水平对齐式。
默认值:TextAlign.Start | | caretColor | [ResourceColor](ts-types.md#resourcecolor) | 设置输入框光标颜色。 | -| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | 通过正则表达式设置输入过滤器。满足表达式的输入允许显示,不满足的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,不支持过滤8到10位的强密码。
- value:设置正则表达式。
- error:正则匹配失败时,返回被忽略的内容。 | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置文本是否可复制。 | +| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | 通过正则表达式设置输入过滤器。匹配表达式的输入允许显示,不匹配的输入将被过滤。仅支持单个字符匹配,不支持字符串匹配。
- value:设置正则表达式。
- error:正则匹配失败时,返回被过滤的内容。 | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。 | ## 事件 @@ -45,14 +45,14 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | 名称 | 功能描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onChange(callback: (value: string) => void) | 输入发生变化时,触发回调。 | -| onCopy8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板复制按钮,触发回调。
- value:复制的文本内容。 | -| onCut8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板剪切按钮,触发回调。
- value:剪切的文本内容。 | -| onPaste8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板粘贴按钮,触发回调。
- value:粘贴的文本内容。 | +| onChange(callback: (value: string) => void) | 输入内容发生变化时,触发该回调。
- value:当前输入的文本内容。 | +| onCopy8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板复制按钮,触发该回调。
- value:复制的文本内容。 | +| onCut8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板剪切按钮,触发该回调。
- value:剪切的文本内容。 | +| onPaste8+(callback:(value: string) => void) | 长按输入框内部区域弹出剪贴板后,点击剪切板粘贴按钮,触发该回调。
- value:粘贴的文本内容。 | ## TextAreaController8+ -TextArea组件的控制器,通过它操作TextArea组件。 +TextArea组件的控制器,目前可通过它设置TextArea组件的光标位置。 ### 导入对象 @@ -75,63 +75,32 @@ caretPosition(value: number): void ## 示例 - -### 多行文本输入 - ```ts // xxx.ets @Entry @Component -struct TextAreaExample1 { - controller: TextAreaController = new TextAreaController() +struct TextAreaExample { @State text: string = '' + controller: TextAreaController = new TextAreaController() + build() { Column() { - TextArea({ placeholder: 'input your word', controller: this.controller}) - .placeholderColor("rgb(0,0,225)") - .placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic }) - .textAlign(TextAlign.Center) - .caretColor(Color.Blue) - .height(50) - .fontSize(30) - .fontWeight(FontWeight.Bold) - .fontFamily("sans-serif") - .fontStyle(FontStyle.Normal) - .fontColor(Color.Red) - .inputFilter('^[\u4E00-\u9FA5A-Za-z0-9_]+$',(value: string) => { - console.info("hyb"+value) - }) + TextArea({ placeholder: 'input your word', controller: this.controller }) + .placeholderFont({ size: 14, weight: 400 }) + .width(400) + .margin(20) + .fontSize(14) .onChange((value: string) => { this.text = value - this.controller.caretPosition(-1) }) - Text(this.text).width('90%') - } + Text(this.text) + Button('Set caretPosition 1') + .margin(15) + .onClick(() => { + // 设置光标位置到第一个字符后 + this.controller.caretPosition(1) + }) + }.width('100%') } } ``` - -![zh-cn_image_0000001251087311](figures/zh-cn_image_0000001251087311.gif) - - -### 设置光标 - -```ts -// xxx.ets -@Entry -@Component -struct TextAreaExample2 { - controller: TextAreaController = new TextAreaController() - build() { - Column() { - TextArea({ placeholder: 'input your word',controller:this.controller }) - Button('caretPosition') - .onClick(() => { - this.controller.caretPosition(4) - }) - } - } -} -``` - -![zh-cn_image_0000001252653499](figures/zh-cn_image_0000001252653499.png) 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-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 3ef11f73e3e90adfc0eccd69fa76bbf51027be4d..1e6a02dd7a8cbd08fb7d8ce6a942123103e9bdfd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -59,13 +59,6 @@ SideBarContainer( type?: SideBarContainerType ) | Start | 侧边栏位于容器左侧。 | | End | 侧边栏位于容器右侧。 | -## SideBarPosition9+枚举说明 - -| 名称 | 描述 | -| -------- | -------- | -| Start | 侧边栏位于容器左侧。 | -| End | 侧边栏位于容器右侧。 | - ## 事件 | 名称 | 功能描述 | 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-methods-datepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 7b442f93de876c69c909970fee623809819adfb1..7330ab11ee2cca5e1c9ba87f81952b0fd4cae3f3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -1,15 +1,12 @@ # 日期滑动选择器弹窗 -根据指定范围的Date创建可以选择日期的滑动选择器,展示在弹窗上。 +根据指定的日期范围创建日期滑动选择器,展示在弹窗上。 > **说明:** +> > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 权限列表 - -无 - ## DatePickerDialog.show show(options?: DatePickerDialogOptions) @@ -17,83 +14,70 @@ show(options?: DatePickerDialogOptions) 定义日期滑动选择器弹窗并弹出。 - DatePickerDialogOptions参数说明 + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | -------- | -------- | -------- | -------- | -------- | - | start | Date | 否 | Date('1970-1-1') | 指定选择器的起始日期。 | - | end | Date | 否 | Date('2100-12-31') | 指定选择器的结束日期。 | - | selected | Date | 否 | 当前系统日期 | 设置选中项的日期。 | - | lunar | boolean | 否 | false | 日期是否显示农历。 | - | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 点击弹窗中确定按钮时触发。 | - | onCancel | () => void | 否 | - | 点击弹窗中取消按钮时触发。 | - | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 滑动选择器,当前选择项改变时触发。 | + | start | Date | 否 | Date('1970-1-1') | 设置选择器的起始日期。 | + | end | Date | 否 | Date('2100-12-31') | 设置选择器的结束日期。 | + | selected | Date | 否 | 当前系统日期 | 设置当前选中的日期。 | + | lunar | boolean | 否 | false | 日期是否显示为农历。 |确定 + | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 点击弹窗中的“确定”按钮时触发该回调。 | + | onCancel | () => void | 否 | - | 点击弹窗中的“取消”按钮时触发该回调。 | + | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | ## 示例 -### 日期滑动选择器(显示农历)示例 ```ts // xxx.ets @Entry @Component -struct DatePickerDialogExample01 { - @State isLunar: boolean = true - selectedDate: Date = new Date("2000-1-1") +struct DatePickerDialogExample { + selectedDate: Date = new Date("2010-1-1") build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("DatePickerDialog").onClick(() => { - DatePickerDialog.show({ - start: new Date("2000-1-1"), - end: new Date("2005-1-1"), - selected: this.selectedDate, - lunar: this.isLunar, - onAccept: (value: DatePickerResult) => { - this.selectedDate.setFullYear(value.year, value.month, value.day) - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("DatePickerDialog:onCancel()") - }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) - } + Column() { + Button("DatePickerDialog") + .margin(20) + .onClick(() => { + DatePickerDialog.show({ + start: new Date("2000-1-1"), + end: new Date("2100-12-31"), + selected: this.selectedDate, + onAccept: (value: DatePickerResult) => { + // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 + this.selectedDate.setFullYear(value.year, value.month, value.day) + console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("DatePickerDialog:onCancel()") + }, + onChange: (value: DatePickerResult) => { + console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) + } + }) }) - }) - } - } -} -``` -### 日期滑动选择器(不显示农历)示例 -```ts -// xxx.ets -@Entry -@Component -struct DatePickerDialogExample02 { - @State isLunar: boolean = false - selectedDate: Date = new Date("2000-1-1") - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("DatePickerDialog").onClick(() => { - DatePickerDialog.show({ - start: new Date("2000-1-1"), - end: new Date("2005-1-1"), - selected: this.selectedDate, - lunar: this.isLunar, - onAccept: (value: DatePickerResult) => { - this.selectedDate.setFullYear(value.year, value.month, value.day) - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("DatePickerDialog:onCancel()") - }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) - } + Button("Lunar DatePickerDialog") + .margin(20) + .onClick(() => { + DatePickerDialog.show({ + start: new Date("2000-1-1"), + end: new Date("2100-12-31"), + selected: this.selectedDate, + lunar: true, + onAccept: (value: DatePickerResult) => { + this.selectedDate.setFullYear(value.year, value.month, value.day) + console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("DatePickerDialog:onCancel()") + }, + onChange: (value: DatePickerResult) => { + console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) + } + }) }) - }) - } + }.width('100%') } } ``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 95cf090c374104933239a351e082ee7bc421e568..25576aa891bb8f00d951d26a3cc62c67156458a6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -3,13 +3,10 @@ 根据指定的选择范围创建文本选择器,展示在弹窗上。 > **说明:** +> > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 权限列表 - -无 - ## TextPickerDialog.show show(options?: TextPickerDialogOptions) @@ -17,21 +14,23 @@ show(options?: TextPickerDialogOptions) 定义文本滑动选择器弹窗并弹出。 - TextPickerDialogOptions参数说明 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------- | -------- | -------- | -------- | -------- | - | range | string[] \| [Resource](../../ui/ts-types.md#resource类型) | 是 | - | 选择器的数据选择范围。 | - | selected | number | 否 | 0 | 选中项在数组中的index值。 | - | value | string | 否 | - | 选中项文本值。当设置了selected参数时,该值不生效。如果该值不在range范围内,则默认取range第一个元素。| - | defaultPickerItemHeight | number \| string | 否 | - | 默认Picker内容项元素高度。 | - | onAccept | (value: TextPickerResult) => void | 否 | - | 点击弹窗中确定按钮时触发。 | - | onCancel | () => void | 否 | - | 点击弹窗中取消按钮时触发。 | - | onChange | (value: TextPickerResult) => void | 否 | - | 滑动选择器,当前选择项改变时触发。 | + + | 参数名 | 参数类型 | 必填 | 参数描述 | + | -------- | -------- | -------- | -------- | + | range | string[] \| [Resource](../../ui/ts-types.md#resource类型) | 是 | 设置文本选择器的选择范围。 | + | selected | number | 否 | 设置选中项的索引值。
默认值:0 | + | value | string | 否 | 设置选中项的文本内容。当设置了selected参数时,该参数不生效。如果设置的value值不在range范围内,则默认取range第一个元素。| + | defaultPickerItemHeight | number \| string | 否 | 设置选择器中选项的高度。 | + | onAccept | (value: TextPickerResult) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | + | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | + | onChange | (value: TextPickerResult) => void | 否 | 滑动弹窗中的选择器使当前选中项改变时触发该回调。 | - TextPickerResult对象说明 - | 名称 | 参数类型 | 描述 | + + | 名称 | 类型 | 描述 | | -------- | -------- | -------- | - | value | string | 选中项文本。 | - | index | number | 选中项在数组中的index值。 | + | value | string | 选中项的文本内容。 | + | index | number | 选中项在选择范围数组中的索引值。 | ## 示例 @@ -40,29 +39,31 @@ show(options?: TextPickerDialogOptions) @Entry @Component struct TextPickerDialogExample { - @State select: number = 1 - private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4'] + @State select: number = 2 + private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TextPickerDialog").onClick(() => { - TextPickerDialog.show({ - range: this.fruits, - selected: this.select, - onAccept: (value: TextPickerResult) => { - console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) - this.select = value.index - }, - onCancel: () => { - console.info("TextPickerDialog:onCancel()") - }, - onChange: (value: TextPickerResult) => { - console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) - } + Column() { + Button("TextPickerDialog") + .margin(20) + .onClick(() => { + TextPickerDialog.show({ + range: this.fruits, + selected: this.select, + onAccept: (value: TextPickerResult) => { + // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项 + this.select = value.index + console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TextPickerDialog:onCancel()") + }, + onChange: (value: TextPickerResult) => { + console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) + } + }) }) - }) - } + }.width('100%') } } ``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 494aabc0122e49cb4a09f9b8e67b0143db07013e..76ea01dc98ffc8ac952cba14b5192b8bebcc26da 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -1,8 +1,9 @@ # 时间滑动选择器弹窗 -默认以00:00至23:59的时间区间创建滑动选择器,展示在弹窗上。 +以24小时的时间区间创建时间滑动选择器,展示在弹窗上。 > **说明:** +> > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 ## TimePickerDialog.show @@ -11,79 +12,64 @@ show(options?: TimePickerDialogOptions) 定义时间滑动选择器弹窗并弹出。 -- options参数 +- TimePickerDialogOptions参数 + | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | - | selected | Date | 否 | 设置选中项的时间。
默认值:当前系统时间 | - | useMilitaryTime | boolean | 否 | 展示时间是否为24小时制。
默认值:false | - | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 点击弹窗中确定按钮时触发。 | - | onCancel | () => void | 否 | 点击弹窗中取消按钮时触发。 | - | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 滑动选择器,当前选择项改变时触发。 | + | selected | Date | 否 | 设置当前选中的时间。
默认值:当前系统时间 | + | useMilitaryTime | boolean | 否 | 展示时间是否为24小时制,默认为12小时制。
默认值:false | + | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | + | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | + | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 滑动弹窗中的选择器使当前选中时间改变时触发该回调。 | ## 示例 -### 时间滑动选择器(24小时制)示例 ```ts // xxx.ets @Entry @Component -struct TimePickerDialogExample01 { - @State isUseMilitaryTime: boolean = true; - private selectTime: Date = new Date('7/22/2022 12:45:00'); +struct TimePickerDialogExample { + private selectTime: Date = new Date('2020-12-25T08:30:00') build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - selected:this.selectTime, - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()"); - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); - } + Column() { + Button("TimePickerDialog 12小时制") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + onAccept: (value: TimePickerResult) => { + // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } - } -} -``` - ![zh-cn_image_0000001118642010](figures/zh-cn_image_0000001118642010.gif) - -### 时间滑动选择器(12小时制)示例 - -```ts -// xxx.ets -@Entry -@Component -struct TimePickerDialogExample02 { - @State isUseMilitaryTime: boolean = false; - - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()"); - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); - } + Button("TimePickerDialog 24小时制") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + useMilitaryTime: true, + onAccept: (value: TimePickerResult) => { + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } + }.width('100%') } } -``` - - ![zh-cn_image_0000001118642020](figures/zh-cn_image_0000001118642020.gif) \ No newline at end of file +``` \ No newline at end of file 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-Account.md b/zh-cn/application-dev/reference/errorcodes/errcode-Account.md index a5a1abe953816488972326325ca9253051991477..e176a23a6f7d23a11f5a3afd3990649183c10d98 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md +++ b/zh-cn/application-dev/reference/errorcodes/errcode-Account.md @@ -1,52 +1,19 @@ -# 账号子系统通用错误码 +# Account错误码 -## 201 权限校验失败 - -### 错误信息 -Permission denied. - -### 可能原因 -该错误码表示权限校验失败,可能原因如下: -1. 调用目标接口时,未申请权限。 -2. 非会话请求方和响应方查询会话信息。 - -### 处理步骤 -1. 请申请相应接口要求的权限。 -2. 请取消非法查询,使用会话请求方和响应方查询会话信息。 - -## 401 参数检查失败 - -### 错误信息 -Parameter check failed. - -### 可能原因 -该错误码表示参数检查失败,可能原因如下: -1. 必选参数没有传入,参数类型错误。 - -### 处理步骤 -1. 请按照参数类型、位置,传入合法的参数。 - -## 801 API不支持 - -### 错误信息 -Capability not supported. - -### 可能原因 -暂无 - -### 处理步骤 -1. 取消调用和调用替代接口。 +以下错误码包括系统帐号和分布式帐号错误码。 ## 12300001 系统服务异常 -### 错误信息 +**错误信息** + System service works abnormally. -### 可能原因 +**可能原因** + 该错误码表示系统服务异常,可能原因如下: -1. 账号管理服务无法正常启动。 -2. 账号管理的IPC对象无法获取。 -3. 账号管理依赖的其他服务无法正常启动或者IPC对象无法获取。 +1. 帐号管理服务无法正常启动。 +2. 帐号管理的IPC对象无法获取。 +3. 帐号管理依赖的其他服务无法正常启动或者IPC对象无法获取。 4. 服务未初始化。 5. 磁盘空间不足。 6. 读写文件异常。 @@ -54,375 +21,328 @@ System service works abnormally. 8. 创建删除文件异常。 9. 读写数据库异常。 -### 处理步骤 -1. 请稍后重试,或重启设备。 +**处理步骤** + +请稍后重试,或重启设备。 ## 12300002 无效参数 -### 错误信息 + +**错误信息** + Invalid parameter. -### 可能原因 +**可能原因** + 该错误码表示传入无效的参数,可能原因如下: 1. 用户名为空。 -2. 系统账号用户名长度大于1024。 -3. 分布式账号用户名长度大于256。 -4. 系统账号id小于0、小于100或大于1000。 -5. 分布式账号id长度大于512。 -6. 分布式账号传入不支持的事件类型。 +2. 系统帐号用户名长度大于1024。 +3. 分布式帐号用户名长度大于256。 +4. 系统帐号id小于0、小于100或大于1000。 +5. 分布式帐号id长度大于512。 +6. 分布式帐号传入不支持的事件类型。 7. 域名为空。 8. 域名长度大于128。 -9. 域账号为空。 -10. 域账号长度大于512。 +9. 域帐号为空。 +10. 域帐号长度大于512。 11. 约束为空。 12. 约束长度大于128。 13. 传入无效的认证和查询参数。 -14. 提供的系统账号头像编码字符串长度超过4KB。 -15. 提供的分布式账号头像编码字符串长度超过2MB。 +14. 提供的系统帐号头像编码字符串长度超过4KB。 +15. 提供的分布式帐号头像编码字符串长度超过2MB。 16. 提供非jpg和png的图片。 -17. 应用账号名长度超过512。 +17. 应用帐号名长度超过512。 18. 鉴权类型长度超过1024。 19. 令牌长度超过1024。 20. 键名长度超过1024。 21. 自定义数据值长度超过1024。 -### 处理步骤 -1. 请传入正确的参数。 +**处理步骤** + +请传入正确的参数。 + +## 12300003 帐号不存在 -## 12300003 账号不存在 +**错误信息** -### 错误信息 -The account does not exist. +The account does not exist. -### 可能原因 -该错误码表示操作的账号不存在,可能原因如下: -1. 查询/激活/删除未创建的账号。 -2. 查询/激活/删除已删除的账号。 -3. 为已删除的账号设置约束/用户名/头像。 -4. 更新未创建的账号。 -5. 为不存在的账号设置/取消账号信息访问授权。 -6. 为不存在的账号设置/删除/查询密码。 -7. 为不存在的账号设置/删除令牌。 -8. 为不存在的账号设置额外信息。 -9. 为不存在的账号设置/删除凭据。 -10. 为不存在的账号设置自定义数据。 -11. 为不存在的账号使能分布式同步功能。 +**可能原因** -### 处理步骤 -1. 请检查账号是否存在。 +该错误码表示操作的帐号不存在,可能原因如下: +1. 查询/激活/删除未创建的帐号。 +2. 查询/激活/删除已删除的帐号。 +3. 为已删除的帐号设置约束/用户名/头像。 +4. 更新未创建的帐号。 +5. 为不存在的帐号设置/取消帐号信息访问授权。 +6. 为不存在的帐号设置/删除/查询密码。 +7. 为不存在的帐号设置/删除令牌。 +8. 为不存在的帐号设置额外信息。 +9. 为不存在的帐号设置/删除凭据。 +10. 为不存在的帐号设置自定义数据。 +11. 为不存在的帐号使能分布式同步功能。 -## 12300004 操作受限账号 +**处理步骤** + +请检查帐号是否存在。 + +## 12300004 操作受限帐号 + +**错误信息** -### 错误信息 The specified account is restricted. -### 可能原因 -该错误码表示操作的是受限账号,可能原因如下: +**可能原因** + +该错误码表示操作的是受限帐号,可能原因如下: 1. 删除系统保留用户。 2. 查询系统保留用户的约束源类型。 -3. 创建id为0-100的账号。 +3. 创建id为0-100的帐号。 + +**处理步骤** -### 处理步骤 -1. 指定id为系统保留用户,无法操作。 +指定id为系统保留用户,无法操作。 ## 12300005 监听器已注册 -### 错误信息 +**错误信息** + The listener has been registered. -### 可能原因 +**可能原因** + 该错误码表示监听器已注册,可能原因如下: -1. 当前应用向系统注册一个已经注册过的监听器,无法重复注册。 +当前应用向系统注册一个已经注册过的监听器,无法重复注册。 + +**处理步骤** -### 处理步骤 -1. 请取消注册,或使用未注册过的监听器重新注册。 +请取消注册,或使用未注册过的监听器重新注册。 ## 12300006 监听器未注册 -### 错误信息 +**错误信息** + The Listener is not registered. -### 可能原因 +**可能原因** + 该错误码表示监听器未注册,可能原因如下: -1. 解注册一个未注册过的监听器。 +解注册一个未注册过的监听器。 -### 处理步骤 -1. 请使用注册的监听器执行解注册操作 +**处理步骤** + +请使用注册的监听器执行解注册操作 ## 12300007 PIN码输入器已注册 -### 错误信息 -The PIN inputer already exists. +**错误信息** + +The PIN inputer already exists. + +**可能原因** -### 可能原因 该错误码表示PIN码输入器已注册,可能原因如下: -1. PIN码输入器已注册,解注册之前无法重复注册。 +PIN码输入器已注册,解注册之前无法重复注册。 + +**处理步骤** + +PIN码输入器已存在,请勿重复操作。 + +## 12300008 帐号已存在 + +**错误信息** + +The account already exists. + +**可能原因** -### 处理步骤 -1. PIN码输入器已存在,请勿重复操作。 +该错误码表示帐号已存在,可能原因如下: +创建已存在的帐号。 -## 12300008 账号已存在 +**处理步骤** -### 错误信息 -The account already exists. +请取消创建,或使用其他账户号名重试。 -### 可能原因 -该错误码表示账号已存在,可能原因如下: -1. 创建已存在的账号。 +## 12300009 帐号已激活 -### 处理步骤 -1. 请取消创建,或使用其他账户号名重试。 +**错误信息** -## 12300009 账号已激活 +The account has been activated. -### 错误信息 -The account has been activated. +**可能原因** -### 可能原因 -该错误码表示账号已激活,可能原因如下: -1. 激活已激活的账号。 +该错误码表示帐号已激活,可能原因如下: +激活已激活的帐号。 -### 处理步骤 -1. 当前账号已激活,请勿重复操作。 +**处理步骤** -## 12300010 账号服务忙 +当前帐号已激活,请勿重复操作。 -### 错误信息 -The account service is busy. +## 12300010 帐号服务忙 -### 可能原因 -该错误码表示账号服务忙,可能原因如下: +**错误信息** + +The account service is busy. + +**可能原因** + +该错误码表示帐号服务忙,可能原因如下: 1. 短时间提交重复请求,如重复激活、重复设置等。 -2. 应用账号的认证会话数量超过256,无法处理新的认证请求。 +2. 应用帐号的认证会话数量超过256,无法处理新的认证请求。 -### 处理步骤 -1. 请等待一段时间后重试,并降低调用频率。 +**处理步骤** -## 12300011 账号数量已达上限 +请等待一段时间后重试,并降低调用频率。 + +## 12300011 帐号数量已达上限 + +**错误信息** -### 错误信息 The account number has reached the upper limit. -### 可能原因 -该错误码表示账号数量已达上限,可能原因如下: -1. 创建系统账号/应用账号时,已存在1000个账号。 +**可能原因** + +该错误码表示帐号数量已达上限,可能原因如下: +创建系统帐号/应用帐号时,已存在1000个帐号。 -### 处理步骤 -1. 请删除其他账号后再创建。 +**处理步骤** + +请删除其他帐号后再创建。 ## 12300012 不支持多用户 -### 错误信息 +**错误信息** + Multi-user is not supported. -### 可能原因 +**可能原因** + 该错误码表示不支持多用户,可能原因如下: -1. 当前设备不支持多用户,无法创建账号 +当前设备不支持多用户,无法创建帐号 -### 处理步骤 -1. 无法创建其他账号,请取消创建 +**处理步骤** -## 12300013 不支持的账号类型 +无法创建其他帐号,请取消创建 + +## 12300013 不支持的帐号类型 + +**错误信息** -### 错误信息 The account type is not supported. -### 可能原因 -该错误码表示提供了不支持的账号类型,可能原因如下: -1. 当前设备不支持创建管理员账号 +**可能原因** + +该错误码表示提供了不支持的帐号类型,可能原因如下: +当前设备不支持创建管理员帐号 -### 处理步骤 -1. 请创建非管理员账号 +**处理步骤** + +请创建非管理员帐号 ## 12300014 可信等级不支持 -### 错误信息 +**错误信息** + The trust level is not supported. -### 可能原因 +**可能原因** + 该错误码表示提供了可信等级不支持,可能原因如下: -1. 传入系统不支持的可信等级。 +传入系统不支持的可信等级。 + +**处理步骤** -### 处理步骤 -1. 请输入正确的可信等级。 +请输入正确的可信等级。 ## 12300015 认证类型不支持 -### 错误信息 +**错误信息** + The auth type is not supported. -### 可能原因 +**可能原因** + 该错误码表示提供了认证类型不支持,可能原因如下: -1. 传入系统不支持的认证类型。 +传入系统不支持的认证类型。 + +**处理步骤** -### 处理步骤 -1. 请提供系统支持的认证类型。 +请提供系统支持的认证类型。 ## 12300016 认证超时 -### 错误信息 +**错误信息** + The auth service is timeout. -### 可能原因 +**可能原因** + 该错误码表示认证超时,可能原因如下: 1. 认证录入超过三分钟。 2. 认证服务因网络原因无法及时响应而超时。 -### 处理步骤 +**处理步骤** + 1. 认证录入超时,请重试。 2. 请确认网络环境无问题后重试。 ## 12300017 认证服务忙 -### 错误信息 +**错误信息** + The auth service is busy. -### 可能原因 +**可能原因** + 该错误码表示认证服务忙,可能原因如下: -1. 认证总数超过5个。 +认证总数超过5个。 + +**处理步骤** -### 处理步骤 -1. 当前认证服务忙,请稍后重试。 +当前认证服务忙,请稍后重试。 ## 12300018 认证服务锁定 -### 错误信息 +**错误信息** + The auth service is locked. -### 可能原因 +**可能原因** + 该错误码表示认证服务锁定,可能原因如下: -1. 认证类型错误次数超过上限。 +认证类型错误次数超过上限。 + +**处理步骤** -### 处理步骤 -1. 认证错误次数超过上限,请在freezingTime之后重试。 +认证错误次数超过上限,请在freezingTime之后重试。 ## 12300019 凭据不存在 -### 错误信息 +**错误信息** + The credential does not exist. -### 可能原因 +**可能原因** + 该错误码表示凭据不存在,可能原因如下: 1. 认证未录入的凭据类型。 2. 查询未录入的凭据类型。 3. 删除未录入的凭据类型。 -### 处理步骤 -1. 请确认凭据类型是否存在。 - -## 12300020 无效的contextId - -### 错误信息 -The contextId is invalid. - -### 可能原因 -该错误码表示contextId无效,可能原因如下: -1. 传入取消的contexId未发起认证录入或已经完成。 - -### 处理步骤 -1. 请输入正确的contextId。 +**处理步骤** -# 应用账号错误码 +请确认凭据类型是否存在。 -## 12400001 应用不存在 - -### 错误信息 -The application does not exist. - -### 可能原因 -该错误码表示应用不存在,可能原因如下: -1. 设置访问权限时,目标应用不存在。 -2. 设置开放授权时,目标应用不存在。 - -### 处理步骤 -1. 请取消设置,或使用已安装的应用包名重试。 - -## 12400002 账号认证器服务不存在 - -### 错误信息 -The account authenticator service does not exist. -### 可能原因 -该错误码表示账号认证器服务不存在,可能原因如下: -1. 请求鉴权时,账号所属应用不支持认证器服务。 -2. 隐式添加账号时,账号所属应用不支持认证器服务。 -3. 验证指定账号的凭据时,该账号所属应用不支持认证器服务。 -4. 设置应用的认证器属性时,指定的应用不支持认证器服务。 - -### 处理步骤 -1. 请取消操作,或使用支持认证器服务的应用的包名重试。 - -## 12400003 账号认证器服务异常 - -### 错误信息 -The account authenticator service works abnormally. -### 可能原因 -该错误码表示账号认证器服务异常,可能原因如下: -1. 三方应用的鉴权服务接连失败。 - -### 处理步骤 -1. 请重试或重启系统。 - -## 12400004 鉴权类型不存在 - -### 错误信息 -The auth type does not exist. -### 可能原因 -该错误码表示鉴权类型不存在,可能原因如下: -1. 查询/删除令牌时,指定的鉴权类型不存在。 - -### 处理步骤 -1. 请使用存在的鉴权类型查询/删除。 - -## 12400005 会话不存在 - -### 错误信息 -The session does not exist. -### 可能原因 -该错误码表示会话不存在,可能原因如下: -1. 查询不存在的会话回调。 - -### 处理步骤 -1. 请使用已成功打开的会话标识查询会话回调。 - -## 12400006 授权列表已达上限 - -### 错误信息 -The size of authorization list reaches upper limit. -### 可能原因 -该错误码表示授权列表已达上限,可能原因如下: -1. 设置访问/开放授权时,授权列表的大小超过1024。 - -### 处理步骤 -1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。 - -## 12400007 令牌数量已达上限 - -### 错误信息 -The number of token reaches upper limit. -### 可能原因 -该错误码表示令牌数量已达上限,可能原因如下: -1. 添加令牌时,目标账号的令牌数量已达1024。 - -### 处理步骤 -1. 请取消添加操作,或者删除已存在的令牌后再添加。 +## 12300020 无效的contextId -## 12400008 自定义数据的数量已达上限 +**错误信息** -### 错误信息 -The number of custom data reaches upper limit. -### 可能原因 -该错误码表示自定义数据的数量已达上限,可能原因如下: -1. 设置自定义数据时,目标账号的自定义数据数量已达512。 +The contextId is invalid. -### 处理步骤 -1. 请取消设置操作,或者删除已存在的自定义数据。 +**可能原因** -## 12400009 自定义数据不存在 +该错误码表示contextId无效,可能原因如下: +传入取消的contexId未发起认证录入或已经完成。 -### 错误信息 -The custom data does not exist. -### 可能原因 -该错误码表示自定义数据不存在,可能原因如下: -1. 查询账号的自定义数据时,输入的键名不存在。 +**处理步骤** -### 处理步骤 -1. 请使用存在的自定义数据的键名查询。 \ No newline at end of file +请输入正确的contextId。 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/errorcode-AccessToken.md b/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md similarity index 61% rename from zh-cn/application-dev/reference/errorcodes/errorcode-AccessToken.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md index a4672eeb695ba0371e8ee31d5bdca10b57ee80e9..16a8cf53764e369e6b3f916063da3c10c5bb4b9c 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-AccessToken.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @@ -1,140 +1,134 @@ -# AccessToken错误码 - -## 401 参数错误 - -### 错误信息 -Parameter error.${messageInfo}. - -### 可能原因 -该错误码表示js参数解析出现错误,可能原因如下。 -1. 入参数量不足。 -2. 参数类型错误。 - -### 处理步骤 -1. 检查入参,补充足够的入参数量。 -2. 检查入参,修正参数类型错误。 - - -## 201 权限校验失败 - -### 错误信息 -Permission denied.${messageInfo}. - -### 可能原因 -该错误码表示调用接口的应用进程未授权该接口所需目标权限,可能原因如下。 -1. 调用接口的应用进程未申请目标权限。 -2. 在该目标权限为用户授权类型的权限情况下,调用接口的应用进程未被用户授予该目标权限。 - -### 处理步骤 -1. 检查调用接口的应用进程是否申请了该权限。 -2. 在该目标权限为用户授权类型的权限情况下,检查调用接口的应用进程是否已被授予该权限。 - - -## 12100001 入参错误 - -### 错误信息 -Parameter invalid, message is ${messageInfo}. - -### 可能原因 -该错误码表示参数校验出现错误,可能原因如下。 -1. tokenId值为0。 -2. 指定的权限名为空或者权限名长度大于256。 -3. 请求授权/撤销权限的flag取值非法。 -4. 注册监听的参数检查错误。 - -### 处理步骤 -1. 检查入参,修正参数值为合法值。 - - -## 12100002 tokenId不存在 - -### 错误信息 -TokenId does not exist. - -### 可能原因 -1. 指定的tokenid不存在。 -2. 指定的tokenId对应的进程非应用进程。 - -### 处理步骤 -检查入参,修正参数值为有效值。 - - -## 12100003 权限名不存在 - -### 错误信息 -Permission does not exist. - -### 可能原因 -1. 指定的permissionName不存在。 -2. 请求授权/撤销权限场景下,指定的应用tokenid未申请过指定的permissionName。 -3. 权限使用记录场景下,指定的permissionName非用户授权的敏感权限。 - -### 处理步骤 -检查入参,修正参数值为有效值。[权限列表](../../security/permission-list.md)。 - - -## 12100004 接口未配套使用 - -### 错误信息 -The listener interface is not used together. - -### 可能原因 -该错误码表示监听器接口未配套使用,可能原因如下。 -1. 当前接口再未配套使用的情况下,重复调用。 -2. 当前接口再未配套使用的情况下,单独调用。 - -### 处理步骤 -1. 检查当前接口是否有配套使用,如调用启动记录的接口后,在未调用停止记录的接口前,不可再次使用相同的入参调用启动记录接口。 -2. 检查当前接口是否有配套使用,如停止记录的接口需要在启动记录的接口调用之后方可调用,注销监听接口需要在注册监听接口调用之后方可调用。 - - -## 12100005 监听器数量超过限制 - -### 错误信息 -The number of listeners exceeds the limit. - -### 可能原因 -该错误码表示当前监听器数量超过限制200. - -### 处理步骤 -及时释放已注册的无用的监听器。 - - -## 12100006 指定的应用不支持被授予或被取消授予指定的权限 - -### 错误信息 -The specified application does not support the permissions granted or ungranted as specified. - -### 可能原因 -1. 输入的tokenid是远端设备的身份标识,尚未支持分布式授权和取消授权。 -2. 入参指定的tokenid为沙箱应用,被禁止申请指定的权限。 - -### 处理步骤 -1. 请确认tokenid的获取方式是否正确。 -2. 确认待授权的沙箱应用是否为特殊的受限沙箱应用进程,部分模式下的沙箱应用被禁止授予大部分权限。 - - -## 12100007 系统服务工作异常 - -### 错误信息 -Service is abnormal. - -### 可能原因 -该错误码表示系统服务工作异常。 -1. 权限管理服务无法正常启动。 -2. IPC数据读取写入失败。 - -### 处理步骤 -系统服务内部工作异常,请稍后重试,或者重启设备。 - - -## 12100008 内存申请失败 - -### 错误信息 -Out of memory. - -### 可能原因 -系统内存不足。 - -### 处理步骤 -系统内存不足,请稍后重试,或者重启设备。 \ No newline at end of file +# AccessToken错误码 + +## 12100001 入参错误 + +**错误信息** + +Parameter invalid, message is ${messageInfo}. + +**可能原因** + +该错误码表示参数校验出现错误,可能原因如下。 +1. tokenId值为0。 +2. 指定的权限名为空或者权限名长度大于256。 +3. 请求授权/撤销权限的flag取值非法。 +4. 注册监听的参数检查错误。 + +**处理步骤** + +检查入参,修正参数值为合法值。 + + +## 12100002 tokenId不存在 + +**错误信息** + +TokenId does not exist. + +**可能原因** + +1. 指定的tokenid不存在。 +2. 指定的tokenId对应的进程非应用进程。 + +**处理步骤** + +检查入参,修正参数值为有效值。 + + +## 12100003 权限名不存在 + +**错误信息** + +Permission does not exist. + +**可能原因** + +1. 指定的permissionName不存在。 +2. 请求授权/撤销权限场景下,指定的应用tokenid未申请过指定的permissionName。 +3. 权限使用记录场景下,指定的permissionName非用户授权的敏感权限。 + +**处理步骤** + +检查入参,修正参数值为有效值。[权限列表](../../security/permission-list.md)。 + + +## 12100004 接口未配套使用 + +**错误信息** + +The interface is not used together. + +**可能原因** + +该错误码表示监听器接口未配套使用,可能原因如下。 +1. 当前接口再未配套使用的情况下,重复调用。 +2. 当前接口再未配套使用的情况下,单独调用。 + +**处理步骤** + +1. 检查当前接口是否有配套使用,如调用启动记录的接口后,在未调用停止记录的接口前,不可再次使用相同的入参调用启动记录接口。 +2. 检查当前接口是否有配套使用,如停止记录的接口需要在启动记录的接口调用之后方可调用,注销监听接口需要在注册监听接口调用之后方可调用。 + + +## 12100005 监听器数量超过限制 + +**错误信息** + +The number of listeners exceeds the limit. + +**可能原因** + +该错误码表示当前监听器数量超过限制200. + +**处理步骤** + +及时释放已注册的无用的监听器。 + + +## 12100006 指定的应用不支持被授予或被取消授予指定的权限 + +**错误信息** + +The specified application does not support the permissions granted or ungranted as specified. + +**可能原因** + +1. 输入的tokenid是远端设备的身份标识,尚未支持分布式授权和取消授权。 +2. 入参指定的tokenid为沙箱应用,被禁止申请指定的权限。 + +**处理步骤** + +1. 请确认tokenid的获取方式是否正确。 +2. 确认待授权的沙箱应用是否为特殊的受限沙箱应用进程,部分模式下的沙箱应用被禁止授予大部分权限。 + + +## 12100007 系统服务工作异常 + +**错误信息** + +Service is abnormal. + +**可能原因** + +该错误码表示系统服务工作异常。 +1. 权限管理服务无法正常启动。 +2. IPC数据读取写入失败。 + +**处理步骤** + +系统服务内部工作异常,请稍后重试,或者重启设备。 + + +## 12100008 内存申请失败 + +**错误信息** + +Out of memory. + +**可能原因** + +系统内存不足。 + +**处理步骤** + +系统内存不足,请稍后重试,或者重启设备。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md b/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md new file mode 100644 index 0000000000000000000000000000000000000000..e9d1820c857b5bf10b2424e3aca47f9e96460033 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md @@ -0,0 +1,134 @@ +# 应用帐号错误码 + +## 12400001 应用不存在 + +**错误信息** + +The application does not exist. + +**可能原因** + +该错误码表示应用不存在,可能原因如下: +1. 设置访问权限时,目标应用不存在。 +2. 设置开放授权时,目标应用不存在。 + +**处理步骤** + +请取消设置,或使用已安装的应用包名重试。 + +## 12400002 帐号认证器服务不存在 + +**错误信息** + +The account authenticator service does not exist. +**可能原因** + +该错误码表示帐号认证器服务不存在,可能原因如下: +1. 请求鉴权时,帐号所属应用不支持认证器服务。 +2. 隐式添加帐号时,帐号所属应用不支持认证器服务。 +3. 验证指定帐号的凭据时,该帐号所属应用不支持认证器服务。 +4. 设置应用的认证器属性时,指定的应用不支持认证器服务。 + +**处理步骤** + +请取消操作,或使用支持认证器服务的应用的包名重试。 + +## 12400003 帐号认证器服务异常 + +**错误信息** + +The account authenticator service works abnormally. +**可能原因** + +该错误码表示帐号认证器服务异常,可能原因如下: +三方应用的鉴权服务接连失败。 + +**处理步骤** + +请重试或重启系统。 + +## 12400004 鉴权类型不存在 + +**错误信息** + +The auth type does not exist. +**可能原因** + +该错误码表示鉴权类型不存在,可能原因如下: +查询/删除令牌时,指定的鉴权类型不存在。 + +**处理步骤** + +请使用存在的鉴权类型查询/删除。 + +## 12400005 会话不存在 + +**错误信息** + +The session does not exist. + +**可能原因** + +该错误码表示会话不存在,可能原因如下: + +查询不存在的会话回调。 + +**处理步骤** + +请使用已成功打开的会话标识查询会话回调。 + +## 12400006 授权列表已达上限 + +**错误信息** + +The size of authorization list reaches upper limit. +**可能原因** + +该错误码表示授权列表已达上限,可能原因如下: +设置访问/开放授权时,授权列表的大小超过1024。 + +**处理步骤** +1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。 + +## 12400007 令牌数量已达上限 + +**错误信息** + +The number of token reaches upper limit. +**可能原因** + +该错误码表示令牌数量已达上限,可能原因如下: +添加令牌时,目标帐号的令牌数量已达1024。 + +**处理步骤** + +请取消添加操作,或者删除已存在的令牌后再添加。 + +## 12400008 自定义数据的数量已达上限 + +**错误信息** + +The number of custom data reaches upper limit. +**可能原因** + +该错误码表示自定义数据的数量已达上限,可能原因如下: +设置自定义数据时,目标帐号的自定义数据数量已达512。 + +**处理步骤** + +请取消设置操作,或者删除已存在的自定义数据。 + +## 12400009 自定义数据不存在 + +**错误信息** + +The custom data does not exist. + +**可能原因** + +该错误码表示自定义数据不存在,可能原因如下: +查询帐号的自定义数据时,输入的键名不存在。 + +**处理步骤** + +请使用存在的自定义数据的键名查询。 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-huks.md b/zh-cn/application-dev/reference/errorcodes/errorcode-huks.md new file mode 100644 index 0000000000000000000000000000000000000000..0baec0448e812c078b0f89b2f7d983960460ffdd --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-huks.md @@ -0,0 +1,223 @@ +# huks错误码 + +## 12000001 该子功能不支持(特性) + +**错误信息** + +``${messageInfo}`` mode is not support in current device. + +**可能原因** +支持API,但是不支持API内部某些子特性(功能),如算法参数。 + +**处理步骤** + +调整API参数,使用可替代可支持的参数。 + +## 12000002 缺少密钥算法参数 +**错误信息** + +Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param set. + +**可能原因** + +使用密钥时缺少相关参数。 + +**处理步骤** + +1. 查看errorMessage确认缺少的密钥参数。 +2. 添加对应的正确的密钥参数。 + +## 12000003 无效的密钥算法参数 + +**错误信息** + +``${messageInfo}`` argument is invalid. User should make sure using the correct value. + +**可能原因** + +使用密钥时无效相关参数。 + +**处理步骤** + +1. 查看errorMessage确认无效的的密钥参数名。 +2. 修改对应的密钥参数。 + +## 12000004 文件错误 + +**错误信息** + +Read file failed. or Write file failed. + +**可能原因** + +文件操作错误。 + +**处理步骤** + +1. 查看是否磁盘空间已经写满、文件系统是否有其他异常。 +2. 清理磁盘。 + +## 12000005 进程通信错误 + +**错误信息** + +IPC communication timeout. or Receive message from IPC failed. + +**可能原因** + +进程通信错误。 + +**处理步骤** + +查看错误信息,排查是否进程IPC通信问题。 + +## 12000006 算法库操作失败 + +**错误信息** + +Error occured in crypto engine. + +**可能原因** + +该错误码表示算法库操作失败,可能原因如下。 + +1. 算法库加解密错误,可能是密文数据不对。 +2. 密钥参数不正确。 + +**处理步骤** + +1. 排查密文数据是否正确。 +2. 排查加解密参数是否正确。 + +## 12000007 密钥访问失败 - 密钥已失效 + +**错误信息** + +This credential is already invalidated permanently. + +**可能原因** + +该错误码表示密钥访问失败 - 密钥已失效,可能原因如下。 + +1. 该密钥设置了清除密码失效的用户认证访问控制属性,清除过设备密钥导致密钥失效。 +2. 该密钥设置了新录入生物特征失效的用户认证访问控制属性,由于录入过新的指纹或人脸导致该密钥失败。 + +**处理步骤** + +1. 确认日志是哪种方式导致的认证不通过。 +2. 如果使用了正确参数,但是失效控制导致认证不通过,则该密钥已经无法使用。 + +## 12000008 密钥访问失败 - 密钥认证失败 + +**错误信息** + +Verify authtoken failed. + +**可能原因** + +该密钥设置了用户认证访问控制属性,由于challenge参数不正确导致无法通过认证。 + +**处理步骤** + +1. 检查userIAM认证的challenge参数组装是否正确。 +2. 如果是challenge参数不正确导致,则修改正确的组装方式,使用huks生成challenge组装,并传入userIAM重新认证。 + +## 12000009 密钥访问失败 - 密钥访问超时 + +**错误信息** + +This authtoken is already timeout. + +**可能原因** + +该密钥设置了用户认证访问控制属性,由于使用时间窗timeout导致无法通过认证。 + +**处理步骤** + +如果是timeout导致不正确,则重新触发密钥init并重新认证,使得认证时间和密钥init时间小于设置的timeout时间。 + +## 12000010 密钥操作会话数已达上限 + +**错误信息** + +The number of session has reached limit. + +**可能原因** + +同时使用huks进行密钥会话操作的调用方(同应用或者跨应用)过多,已经达到上限(15个)。 + +**处理步骤** + +1. 检查同应用内部是否同时存在多个密钥会话操作(init),存在则修改避免同时调用。 +2. 如不存在上述情形,则可能是其它应用同时调用多个会话,通过等待其它应用释放会话后再使用。 + +## 12000011 目标对象不存在 + +**错误信息** + +Queried entity does not exist. + +**可能原因** + +该别名对应的密钥不存在。 + +**处理步骤** + +1. 检查密钥别名是否拼写错误。 +2. 检查改密钥别名对应的密钥是否生成成功。 + +## 12000012 外部错误 + +**错误信息** + +External error ``${messageInfo}``. + +**可能原因** + +外部的硬件出错,文件错误等。 + +**处理步骤** + +拿错误码与日志在社区反馈。 + +## 12000013 密钥设置生物访问控制时,待绑定的凭据不存在 + +**错误信息** + +Queried credential does not exist. + +**可能原因** + +密钥绑定PIN、指纹、人脸时,未录入相关凭据。 + +**处理步骤** + +录入相关凭据,或更改绑定凭据类型。 + +## 12000014 内存不足 + +**错误信息** + +Memory is insufficient. + +**可能原因** + +系统内存不足。 + +**处理步骤** + +开发者释放部分内存或重启。 + +## 12000015 调用其他系统服务失败 + +**错误信息** + +Call ``${messageInfo}`` service to do ``${messageInfo}`` failed. + +**可能原因** + +其他系统服务未启动。 + +**处理步骤** + +开发者等待一段时间后尝试再次触发调用。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..e733f2814fb3f7b90ad431d88461abbffe268b72 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @@ -0,0 +1,89 @@ +# 资源管理错误码 + +## 9001001 无效的资源id + +### 错误信息 +The resId invalid. + +### 错误描述 +当传入的资源id符合类型校验,但却是一个不存在的资源id时,会报出此错误。 + +### 可能原因 +传入的是一个不存在的id值。 + +### 处理步骤 +检查传入参数的资源id是否已有。 + +## 9001002 根据当前资源id,找不到匹配的资源 + +### 错误信息 +The resource not found by resId. + +### 错误描述 +当传入的资源id符合类型校验,但是根据此资源id匹配不到资源时,会报出此错误。 + +### 可能原因 +1、传入的是资源id有误。 + +2、资源解析有误。 + +### 处理步骤 +检查传入的资源id是否符合预期。 + +## 9001003 无效的资源名称 + +### 错误信息 +The resName invalid. + +### 错误描述 +当传入的资源名称符合类型校验,但却是一个不存在的资源名称时,会报出此错误。 + +### 可能原因 +传入的是一个不存在的资源名称。 + +### 处理步骤 +检查传入的资源名称是否符合预期。 + +## 9001004 根据当前资源名称,找不到匹配的资源 + +### 错误信息 +The resource not found by resName. + +### 错误描述 +当传入的资源名称符合类型校验,但是根据此资源名称,匹配不到资源。 + +### 可能原因 +1、传入的是资源名称有误。 + +2、资源解析有误。 + +### 处理步骤 +可先检查传入的资源名称是否符合预期。 + +## 9001005 无效的相对路径 + +### 错误信息 +The resource not found by path. + +### 错误描述 +根据参数相对路径, 找不到对应的资源。 + +### 可能原因 +传入的相对路径有误。 + +### 处理步骤 +可检查传入的相对路径是否符合预期。 + +## 9001006 循环引用 + +### 错误信息 +the resource re-ref too much. + +### 错误描述 +解析引用次数过高。 + +### 可能原因 +出现资源循环引用的情况。 + +### 处理步骤 +查看资源$引用的地方,去除循环引用的情况。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-uitest.md b/zh-cn/application-dev/reference/errorcodes/errorcode-uitest.md new file mode 100644 index 0000000000000000000000000000000000000000..dda3aabebadab92b9937e8f86039344e87329343 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-uitest.md @@ -0,0 +1,87 @@ +# uitest错误码 + +## 17000001 初始化失败 + +**错误信息** + +Initialize failed. + +**错误描述** + +框架初始化失败。 + +**可能原因** + +无法连接到无障碍服务。 + +**处理步骤** + +执行param set persist.ace.testmode.enabled 1,并重启设备。 + +## 17000002 当前无法调用 +**错误信息** + +API does not allow calling concurrently. + +**错误描述** + +当前无法调用API。 + +**可能原因** + +API没有使用await进行异步调用,造成堵塞。 + +**处理步骤** + +检查测试用例,确保异步接口使用await调用。 + +## 17000003 断言失败 +**错误信息** + +Component existence assertion failed. + +**错误描述** + +用户断言失败。 + +**可能原因** + +用户断言存在的控件实际不存在。 + +**处理步骤** + +检查用户断言存在的控件实际是否存在。 + +## 17000004 目标控件/窗口丢失 +**错误信息** + +Component lost/UiWindow lost. + +**错误描述** + +目标控件/窗口丢失,无法进行操作。 + +**可能原因** + +获取到目标控件/窗口后,页面发生变化导致目标丢失。 + +**处理步骤** + +检查获取到目标控件/窗口后,页面是否发生变化导致目标丢失。 + +## 17000005 操作不支持 +**错误信息** + +This operation is not supported. + +**错误描述** + +UI对象不支持该操作。 + +**可能原因** + +当前界面控件/窗口属性不支持该操作。 + +**处理步骤** + +检查当前界面控件/窗口属性是否该操作。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md b/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md new file mode 100755 index 0000000000000000000000000000000000000000..559f2ba4a7e76e966212fc53bb96e88270e1c09a --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md @@ -0,0 +1,39 @@ +# zlib子系统错误码 + +## 900001 传入的源文件错误 + +**错误信息** + +The input source file is invalid. + +**错误描述** + +当调用compress或decompress接口时,传入源文件无效。 + +**可能原因** + +当调用compress接口时,传入的待压缩的文件不存在;当调用decompress接口时,传入的待解压缩的文件不存在。 + +**处理步骤** + +检查源文件是否存在。 + +## 900002 传入的目标文件错误 + +**错误信息** + +The input destination file is invalid. + +**错误描述** + +当调用compress或decompress接口时,传入目标文件无效。 + +**可能原因** + +1. 当调用compress接口时,传入的目标文件路径无效,如不存在的沙箱路径。 +2. 当调用decompress接口时,传入的目标目录不存在。 + +**处理步骤** + +1. 检查目标文件路径是否正确,不正确填写正确的沙箱路径。 +2. 检查目标文件目录是否存在,不存在新建这个路径。 \ No newline at end of file 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 25ec2c1d5f90c205e85feb869efd7356b70bc7b1..368108ba13572fde86046d1e30febc4dae2551ed 100644 --- a/zh-cn/application-dev/security/cryptoFramework-guidelines.md +++ b/zh-cn/application-dev/security/cryptoFramework-guidelines.md @@ -1,8 +1,211 @@ # 加解密算法库框架开发指导 + +> **说明** +> +> 本开发指导基于API version 9,OH SDK版本3.2.7.3,适用于JS语言开发 + +## 使用密钥对象生成与转换操作 + +**场景说明** + +使用密钥生成操作中,典型的场景有: + +1. 随机生成算法库密钥对象。该对象可用于后续的加解密等操作。 +2. 根据指定数据生成算法库密钥对象(也就是将外部或存储的二进制数据转换为算法库的密钥对象)。该对象可用于后续的加解密等操作。 +3. 获取算法库密钥对象的二进制数据,用于存储或传输。 +> **说明**:密钥对象Key包括对称密钥SymKey和非对称密钥(公钥PubKey和私钥PriKey),其中公钥和私钥组成密钥对KeyPair。密钥之间的具体关系可参考[接口声明](../reference/apis/js-apis-cryptoFramework.md)。 + + +**接口及参数说明** + +详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)。 + +以上场景涉及的常用接口如下表所示: + +|实例名|接口名|描述| +|---|---|---| +|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|根据algName设置的非对称密钥规格,创建非对称密钥生成器对象| +|cryptoFramework|createSymKeyGenerator(algName : string) : SymKeyGenerator|根据algName设置的对称密钥规格,创建对称密钥生成器对象| +|AsyKeyGenerator|generateKeyPair(callback : AsyncCallback\) : void|使用callback方式,随机生成非对称密钥对象KeyPair| +|AsyKeyGenerator|generateKeyPair() : Promise\|使用Promise方式,随机生成非对称密钥对象KeyPair| +|SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|使用callback方式,随机生成对称密钥对象SymKey| +|SymKeyGenerator|generateSymKey() : Promise\|使用Promise方式,随机生成对称密钥对象SymKey| +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | 使用callback方式,根据指定的公钥和私钥二进制数据生成KeyPair对象
(允许公钥/私钥为null,即只传入单一公钥或私钥,生成只携带公钥或私钥的KeyPair对象) | +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | 使用Promise方式,根据指定的公钥和私钥二进制数据生成KeyPair对象
(允许公钥/私钥为null,即只传入单一公钥或私钥,生成只携带公钥或私钥的KeyPair对象) | +| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| 使用callback方式,根据指定的二进制数据,生成对称密钥对象SymKey | +| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| 使用Promise方式,根据指定的二进制数据,生成对称密钥对象SymKey | +| Key | getEncoded() : DataBlob; | 获取Key密钥对象的二进制数据(Key的子类实例包括对称密钥SymKey、公钥PubKey、私钥PriKey) | + +**开发步骤** + +示例1:随机生成非对称密钥KeyPair,并获得二进制数据(场景1、3) + +1. 创建非对称密钥生成器; +2. 通过非对称密钥生成器随机生成非对称密钥; +3. 获取密钥对象的二进制数据; + +以使用Promise方式随机生成RSA密钥(1024位,素数个数为2)为例: + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +function generateAsyKey() { + // 创建非对称密钥生成器 + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // 通过非对称密钥生成器,随机生成非对称密钥 + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let pubKey = globalKeyPair.pubKey; + let priKey = globalKeyPair.priKey; + // 获取非对称密钥的二进制数据 + pkBlob = pubKey.getEncoded(); + skBlob = priKey.getEncoded(); + AlertDialog.show({ message : "pk bin data" + pkBlob.data} ); + AlertDialog.show({ message : "sk bin data" + skBlob.data} ); + }) +} +``` + +示例2:随机生成对称密钥SymKey,并获得二进制数据(场景1、3) + +1. 创建对称密钥生成器; +2. 通过对称密钥生成器随机生成对称密钥; +3. 获取算法库密钥对象的二进制数据; + +以使用Promise方式随机生成AES密钥(256位)为例: + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 字节流以16进制输出 +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +function testGenerateAesKey() { + // 创建对称密钥生成器 + let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256'); + // 通过密钥生成器随机生成对称密钥 + let promiseSymKey = symKeyGenerator.generateSymKey(); + promiseSymKey.then( key => { + // 获取对称密钥的二进制数据,输出长度为256bit的字节流 + let encodedKey = key.getEncoded(); + console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data)); + }) +} +``` + +示例3:根据指定的RSA非对称密钥二进制数据,生成KeyPair对象(场景2) + +1. 获取RSA二进制密钥数据封装成DataBlob对象,按keysize(32位) 、nsize(keysize/8)、 esize(e实际长度)、dsize(keysize/8)、nval(大数n的二进制数据)、eval(大数e的二进制数据)和dval(大数d的二进制数据)拼接形成。 +2. 调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。 + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +function convertAsyKey() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024"); + // 公钥二进制数据 + let pkval = new Uint8Array([0,4,0,0,128,0,0,0,3,0,0,0,0,0,0,0,182,22,137,81,111,129,17,47,33,97,67,85,251,53,127,42,130,150,93,144,129,104,14,73,110,189,138,82,53,74,114,86,24,186,143,65,87,110,237,69,206,207,5,81,24,32,41,160,209,125,162,92,0,148,49,241,235,0,71,198,1,28,136,106,152,22,25,249,77,241,57,149,154,44,200,6,0,83,246,63,162,106,242,131,80,227,143,162,210,28,127,136,123,172,26,247,2,194,16,1,100,122,180,251,57,22,69,133,232,145,107,66,80,201,151,46,114,175,116,57,45,170,188,77,86,230,111,45,1,0,1]); + // 封装成DataBlob对象 + let pkBlob = {data : pkval}; + // 调用密钥转换函数 + let convertKeyPromise = rsaGenerator.convertKey(pkBlob, null); + convertKeyPromise.then( keyPair => { + if (keyPair == null) { + AlertDialog.show({message : "Convert keypair fail"}); + } + AlertDialog.show({message : "Convert KeyPair success"}); + }) +} +``` + +**说明** + +1. nsize和dsize为密钥位数/8,esize为具体的实际长度。 +2. 私钥材料需要包含keysize,nsize,esize,dsize,nval,eval,dval的全部数据,公钥材料中dsize设置为为0,缺省dval的数据。 +3. 公钥和私钥二进制数据为可选项,可单独传入公钥或私钥的数据,生成对应只包含公钥或私钥的KeyPair对象。 +4. keysize、nsize、esize和dsize为32位二进制数据,数据的大小端格式请按设备CPU默认格式,密钥材料(nval、eval、dval)统一为大端格式。 + +示例4:根据指定的ECC非对称密钥二进制数据,生成KeyPair对象(场景2、3) + +1. 获取ECC二进制密钥数据,封装成DataBlob对象。 +2. 调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。 + +```javascript +function convertEccAsyKey() { + let pubKeyArray = new Uint8Array([4,196,55,233,100,227,224,38,38,5,128,81,53,112,129,7,59,189,116,105,182,87,190,85,31,248,172,116,213,7,206,85,190,65,169,193,138,173,232,187,74,54,78,251,29,131,192,223,251,227,170,138,80,7,98,193,216,168,235,114,255,188,70,134,104]); + let priKeyArray = new Uint8Array([255,70,89,220,189,19,41,157,175,173,83,60,74,216,195,96,24,181,231,23,112,247,150,126,15,155,24,79,33,97,31,225]); + let pubKeyBlob = { data: pubKeyArray }; + let priKeyBlob = { data: priKeyArray }; + let generator = cryptoFrameWork.createAsyKeyGenerator("ECC256"); + generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => { + if (error) { + AlertDialog.show({message : "Convert keypair fail"}); + } + AlertDialog.show({message : "Convert KeyPair success"}); + }) +} +``` + +示例5:根据指定的对称密钥二进制数据,生成SymKey对象(场景2、3) + +1. 创建对称密钥生成器; +2. 通过对称密钥生成器,根据指定的对称密钥二进制数据,生成SymKey对象; +3. 获取算法库密钥对象的二进制数据; + +以使用callback方式生成3DES密钥(3DES密钥只能为192位)为例: + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 字节流以16进制输出 +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +function genKeyMaterialBlob() { + let arr = [ + 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, + 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) + let keyMaterial = new Uint8Array(arr); + return {data : keyMaterial}; +} + +function testConvertAesKey() { + // 生成对称密钥生成器 + let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); + // 根据用户指定的数据,生成对称密钥 + let keyMaterialBlob = genKeyMaterialBlob(); + try { + symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => { + if (error) { // 业务逻辑执行错误通过callback的第一个参数返回错误信息 + console.error(`convertKey error, ${error.code}, ${error.message}`); + return; + } + console.info(`key algName: ${key.algName}`); + console.info(`key format: ${key.format}`); + let encodedKey = key.getEncoded(); // 获取对称密钥的二进制数据,输出长度为192bit的字节流 + console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data)); + }) + } catch (error) { // 参数检查的错误以同步的方式立即抛出异常 + console.error(`convertKey failed, ${error.code}, ${error.message}`); + return; + } +} +``` + ## 使用加解密操作 + **场景说明** -使用加解密操作中,典型的场景有: +在数据存储或传输场景中,可以使用加解密操作用于保证数据的机密性,防止敏感数据泄露。使用加解密操作中,典型的场景有: 1. 使用对称密钥的加解密操作 2. 使用非对称密钥的加解密操作 @@ -26,9 +229,9 @@ 示例1:使用对称密钥的加解密操作 -1. 生成对称密钥生成器。 +1. 创建对称密钥生成器。 2. 通过密钥生成器生成对称密钥。 -3. 生成加解密生成器。 +3. 创建加解密生成器。 4. 通过加解密生成器加密或解密数据。 以AES GCM以Promise方式加解密为例: @@ -345,7 +548,8 @@ function encryptMessageCallback() { ## 使用签名验签操作 **场景说明** -使用签名验签操作中,典型的场景有: + +当需要判断接收的数据是否被篡改且是否为指定对象发送的数据时,可以使用签名验签操作。使用签名验签操作中,典型的场景有: 1. 使用RSA签名验签操作 2. 使用ECC签名验签操作 @@ -375,9 +579,9 @@ function encryptMessageCallback() { 示例1:使用RSA签名验签操作 1. 生成RSA密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成RSA非对称密钥。 2. 生成Sign对象。通过createSign接口创建Sign对象,执行初始化操作并设置签名私钥。 -3. 执行签名操作。通过Sign类提供的update接口,添加签名数据,并调用doFinal接口生成数据的签名。 +3. 执行签名操作。通过Sign类提供的update接口,添加签名数据,并调用sign接口生成数据的签名。 4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。 -5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用doFinal接口传入签名进行验签。 +5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用verify接口传入签名进行验签。 ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -545,6 +749,8 @@ function verifyMessageCallback() { **场景说明** +用户指定摘要算法(如SHA256)生成Md实例,并输入单段或多段需要摘要的信息,进行摘要计算更新,并返回消息摘要计算结果,在指定算法后可获取当前算法名与摘要计算长度(字节) + 使用摘要操作的主要场景为: 用户指定摘要算法(如SHA256)生成Md实例,并输入单段或多段需要摘要的信息,进行摘要计算更新,并返回消息摘要计算结果,在指定算法后可获取当前算法名与摘要计算长度(字节) @@ -647,9 +853,9 @@ function doMdByCallback(algName) { **场景说明** -使用签名验签操作中,典型的场景有: +使用密钥协商操作中,典型的场景有: -使用ECDH操作。 +通信双方可以在一个公开的信道上通过相互传送一些消息,共同建立一个安全的共享秘密密钥。 **接口及参数说明** @@ -714,7 +920,9 @@ function ecdhCallback() { **场景说明** -使用消息认证码操作的主要场景为: +消息认证码操作主要应用于身份认证的场景: + +Mac(message authentication code)可以对消息进行完整性校验,通过使用双方共享的密钥,识别出信息伪装篡改等行为 用户指定摘要算法(如SHA256)生成消息认证码Mac实例,输入对称密钥初始化Mac,并传入单段或多段需要摘要的信息,进行消息认证码计算,并获取消息认证码计算结果,在指定算法后可获取当前算法名与消息认证码计算长度(字节)。 @@ -915,3 +1123,497 @@ function doRandByCallback(len) { }); } ``` + +## 使用证书操作 + +**场景说明** + +使用证书操作中,典型的场景有: + +1. 解析X509证书数据生成证书对象。 +2. 获取证书信息,比如:证书版本、证书序列号等。 +3. 获取证书对象的序列化数据。 +4. 获取证书公钥。 +5. 证书验签。 +6. 校验证书有效期。 + +**接口及参数说明** + +详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)。 + +以上场景涉及的常用接口如下表所示: + +| 实例名 | 接口名 | 描述 | +| --------------- | ------------------------------------------------------------ | -------------------------------------------- | +| cryptoFramework | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback) : void | 使用callback方式解析X509证书数据生成证书对象 | +| cryptoFramework | createX509Cert(inStream : EncodingBlob) : Promise | 使用promise方式解析X509证书数据生成证书对象 | +| X509Cert | verify(key : PubKey, callback : AsyncCallback) : void | 使用callback方式进行证书验签 | +| X509Cert | verify(key : PubKey) : Promise | 使用promise方式进行证书验签 | +| X509Cert | getEncoded(callback : AsyncCallback) : void | 使用callback方式获取证书序列化数据 | +| X509Cert | getEncoded() : Promise | 使用promise方式获取证书序列化数据 | +| X509Cert | getPublicKey(callback : AsyncCallback) : void | 使用callback方式获取证书公钥 | +| X509Cert | getPublicKey() : Promise | 使用Promise方式获取证书公钥 | +| X509Cert | checkValidityWithDate(date: string, callback : AsyncCallback) : void | 使用callback方式校验证书有效期 | +| X509Cert | checkValidityWithDate(date: string) : Promise | 使用Promise方式校验证书有效期 | +| X509Cert | getVersion() : number | 获取证书版本 | +| X509Cert | getSerialNumber() : number | 获取证书序列号 | +| X509Cert | getIssuerName() : DataBlob | 获取证书颁发者名称 | +| X509Cert | getSubjectName() : DataBlob | 获取证书主体名称 | +| X509Cert | getNotBeforeTime() : string | 获取证书有效期起始时间 | +| X509Cert | getNotAfterTime() : string | 获取证书有效期截至时间 | +| X509Cert | getSignature() : DataBlob | 获取证书签名 | +| X509Cert | getSignatureAlgName() : string | 获取证书签名算法名称 | +| X509Cert | getSignatureAlgOid() : string | 获取证书签名算法OID | +| X509Cert | getSignatureAlgParams() : DataBlob | 获取证书签名算法参数 | +| X509Cert | getKeyUsage() : DataBlob | 获取证书秘钥用途 | +| X509Cert | getExtKeyUsage() : DataArray | 获取证书扩展秘钥用途 | +| X509Cert | getBasicConstraints() : number | 获取证书基本约束 | +| X509Cert | getSubjectAltNames() : DataArray | 获取证书主体可选名称 | +| X509Cert | getIssuerAltNames() : DataArray | 获取证书颁发者可选名称 | + +**开发步骤** + +示例:解析X509证书数据生成证书对象,并调用对象方法(包含场景1-6) + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 证书数据,此处仅示例,业务需根据场景自行设置 +let certData = "-----BEGIN CERTIFICATE-----\n" ++ "IBzTCCAXCgAwIBAgIGAXKnMKNyMAwGCCqBHM9VAYN1BQAwSTELMAkGA1UEBhMC\n" ++ "04xDjAMBgNVBAoTBUdNU1NMMRAwDgYDVQQLEwdQS0kvU00yMRgwFgYDVQQDEw9S\n" ++ "290Q0EgZm9yIFRlc3QwIhgPMjAxNTEyMzExNjAwMDBaGA8yMDM1MTIzMDE2MDAw\n" ++ "FowSTELMAkGA1UEBhMCQ04xDjAMBgNVBAoTBUdNU1NMMRAwDgYDVQQLEwdQS0kv\n" ++ "00yMRgwFgYDVQQDEw9Sb290Q0EgZm9yIFRlc3QwWTATBgcqhkjOPQIBBggqgRzP\n" ++ "QGCLQNCAATj+apYlL+ddWXZ7+mFZXZJGbcJFXUN+Fszz6humeyWZP4qEEr2N0+a\n" ++ "dwo/21ft232yo0jPLzdscKB261zSQXSoz4wPDAZBgNVHQ4EEgQQnGnsD7oaOcWv\n" ++ "CTrspwSBDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIAxjAMBggqgRzP\n" ++ "QGDdQUAA0kAMEYCIQCEnW5BlQh0vmsOLxSoXYc/7zs++wWyFc1tnBHENR4ElwIh\n" ++ "I1Lwu6in1ruflZhzseWulXwcITf3bm/Y5X1g1XFWQUH\n" ++ "-----END CERTIFICATE-----\n"; + +// string转Uint8Array +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; i++) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// 证书示例 +function certSample() { + let encodingBlob = { + // 将string类型证书数据转为Uint8Array + data: stringToUint8Array(certData), + // 证书格式:支持PEM和DER,此例中对应PEM + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM + }; + + // 创建证书对象 + cryptoFramework.createX509Cert(encodingBlob, function (err, x509Cert) { + if (err != null) { + // 创建证书对象失败 + Console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message); + return; + } + // 创建证书对象成功 + Console.log("createX509Cert success"); + + // 获取证书版本 + let version = x509Cert.getVersion(); + + // 获取证书对象的序列化数据 + x509Cert.getEncoded(function (err, data) { + if (err != null) { + // 获取序列化数据失败 + Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取序列化数据成功 + Console.log("getEncoded success"); + } + }); + + // 获取证书公钥对象 + x509Cert.getPublicKey(function (err, pubKey) { + if (err != null) { + // 获取证书公钥失败 + Console.log("getPublicKey failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取证书公钥成功 + Console.log("getPublicKey success"); + } + }); + + // 业务需通过上级证书对象或本证书对象(自签名)的getPublicKey接口获取公钥对象,此处省略 + let pubKey = null; + + // 证书验签 + x509Cert.verify(pubKey, function (err, data) { + if (err == null) { + // 验签成功 + Console.log("verify success"); + } else { + // 验签失败 + Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + } + }); + + // 时间字符串 + let date = "150527000001Z"; + + // 校验证书有效期 + x509Cert.checkValidityWithDate(date, function (err, data) { + if (err != null) { + // 证书有效期校验失败 + Console.log("checkValidityWithDate failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 证书有效期校验成功 + Console.log("checkValidityWithDate success"); + } + }); + }); +} +``` + +## 使用证书吊销列表操作 + +**场景说明** + +使用证书吊销列表操作中,典型的场景有: + +1. 解析X509证书吊销列表数据生成吊销列表对象。 +2. 获取证书吊销列表信息,比如:证书吊销列表版本、证书吊销列表类型等。 +3. 获取证书吊销列表对象的序列化数据。 +4. 检查证书是否被吊销。 +5. 证书吊销列表验签。 +6. 获取被吊销证书。 + +**接口及参数说明** + +详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)。 + +以上场景涉及的常用接口如下表所示: + +| 实例名 | 接口名 | 描述 | +| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| cryptoFramework | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback) : void | 使用callback方式解析X509证书吊销列表数据生成证书吊销列表对象 | +| cryptoFramework | createX509Crl(inStream : EncodingBlob) : Promise | 使用promise方式解析X509证书吊销列表数据生成证书吊销列表对象 | +| X509Crl | isRevoked(cert : X509Cert, callback : AsyncCallback) : void | 使用callback方式检查证书是否被吊销 | +| X509Crl | isRevoked(cert : X509Cert) : Promise | 使用promise方式检查证书是否被吊销 | +| X509Crl | getType() : string | 获取证书吊销列表类型 | +| X509Crl | getEncoded(callback : AsyncCallback) : void | 使用callback方式获取证书吊销列表序列化数据 | +| X509Crl | getEncoded() : Promise | 使用promise方式获取证书吊销列表序列化数据 | +| X509Crl | verify(key : PubKey, callback : AsyncCallback) : void | 使用callback方式进行证书吊销列表验签 | +| X509Crl | verify(key : PubKey) : Promise | 使用Promise方式进行证书吊销列表验签 | +| X509Crl | getVersion() : number | 获取证书吊销列表版本 | +| X509Crl | getIssuerName() : DataBlob | 获取证书吊销列表颁发者名称 | +| X509Crl | getLastUpdate() : string | 获取证书吊销列表lastUpdate日期 | +| X509Crl | getNextUpdate() : string | 获取证书吊销列表nextUpdate日期 | +| X509Crl | getRevokedCert(serialNumber : number, callback : AsyncCallback) : void | 使用callback方式通过序列号获取证书吊销列表中的被吊销证书 | +| X509Crl | getRevokedCert(serialNumber : number) : Promise | 使用Promise方式通过序列号获取证书吊销列表中的被吊销证书 | +| X509Crl | getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback) : void | 使用callback方式通过X509证书获取证书吊销列表中的被吊销证书 | +| X509Crl | getRevokedCertWithCert(cert : X509Cert) : Promise | 使用Promise方式通过X509证书获取证书吊销列表中的被吊销证书 | +| X509Crl | getRevokedCerts(callback : AsyncCallback>) : void | 使用callback方式获取证书吊销列表的所有被吊销证书 | +| X509Crl | getRevokedCerts() : Promise> | 使用Promise方式获取证书吊销列表的所有被吊销证书 | +| X509Crl | getTbsInfo(callback : AsyncCallback) : void | 使用callback方式获取证书吊销列表的tbsCertList | +| X509Crl | getTbsInfo() : Promise | 使用Promise方式获取证书吊销列表的tbsCertList | +| X509Crl | getSignature() : DataBlob | 获取证书吊销列表的签名 | +| X509Crl | getSignatureAlgName() : string | 获取证书吊销列表的签名算法名称 | +| X509Crl | getSignatureAlgOid() : string | 获取证书吊销列表的签名算法OID | +| X509Crl | getSignatureAlgParams() : DataBlob | 获取证书吊销列表的签名算法参数 | + +**开发步骤** + +示例:解析X509证书吊销列表数据生成证书吊销列表对象,并调用对象方法(包含场景1-6) + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 证书吊销列表数据,此处仅示例,业务需根据场景自行设置 +let crlData = "-----BEGIN X509 CRL-----\n" ++ "MIIBijB0AgEBMA0GCSqGSIb3DQEBCwUAMBMxETAPBgNVBAMMCHJvb3QtY2ExFw0y\n" ++ "MDA2MTkxNjE1NDhaFw0yMDA3MTkxNjE1NDhaMBwwGgIJAMsozRATnap1Fw0yMDA2\n" ++ "MTkxNjEyMDdaoA8wDTALBgNVHRQEBAICEAIwDQYJKoZIhvcNAQELBQADggEBACPs\n" ++ "9gQB+djaXPHHRmAItebZpD3iJ/e36Dxr6aMVkn9FkI8OVpUI4RNcCrywyCZHQJte\n" ++ "995bbPjP7f1sZstOTZS0fDPgJ5SPAxkKOQB+SQnBFrlZSsxoUNU60gRqd2imR0Rn\n" ++ "1r09rP69F6E4yPc9biEld+llLGgoImP3zPOVDD6fbfcvVkjStY3bssVEQ/vjp4a3\n" ++ "/I12U7ZnSe3jaKqaQBoVJppkTFOIOq7IOxf5/IkMPmvRHDeC2IzDMzcUxym0dkny\n" ++ "EowHrjzo0bZVqpHMA2YgKZuwTpVLHk9GeBEK2hVkIoPVISkmiU4HFg0S6z68C5yd\n" ++ "DrAA7hErVgXhtURLbAI=\n" ++ "-----END X509 CRL-----\n"; + +// string转Uint8Array +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; i++) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// 证书吊销列表示例 +function crlSample() { + let encodingBlob = { + // 将string类型证书吊销列表数据转为Uint8Array + data: stringToUint8Array(crlData), + // 证书吊销列表格式:支持PEM和DER,此例中对应PEM + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM + }; + + // 创建证书吊销列表对象 + cryptoFramework.createX509Crl(encodingBlob, function (err, x509Crl) { + if (err != null) { + // 创建证书吊销列表对象失败 + Console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message); + return; + } + // 创建证书吊销列表对象成功 + Console.log("createX509Crl success"); + + // 获取证书吊销列表版本 + let version = x509Crl.getVersion(); + + // 获取证书吊销列表对象的序列化数据 + x509Crl.getEncoded(function (err, data) { + if (err != null) { + // 获取序列化数据失败 + Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取序列化数据成功 + Console.log("getEncoded success"); + } + }); + + // 业务需通过cryptoFramework的createX509Cert生成X509Cert证书对象,此处省略 + let x509Cert = null; + + // 检查证书是否被吊销 + x509Crl.isRevoked(x509Cert, function (err, isRevoked) { + if (err != null) { + // 检查证书是否被吊销失败 + Console.log("isRevoked failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 检查证书是否被吊销成功 + Console.log("isRevoked success, isRevoked? " + isRevoked); + } + }); + + // 业务需通过AsyKeyGenerator的generateKeyPair或convertKey接口获取PubKey对象,此处省略 + let pubKey = null; + + // 证书吊销列表验签 + x509Crl.verify(pubKey, function (err, data) { + if (err == null) { + // 验签成功 + Console.log("verify success"); + } else { + // 验签失败 + Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + } + }); + + // 证书序列号,业务需自行设置 + let serialNumber = 1000; + + // 获取被吊销证书对象 + x509Crl.getRevokedCert(serialNumber, function (err, entry) { + if (err != null) { + // 获取被吊销证书对象失败 + Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取被吊销证书对象成功 + Console.log("getRevokedCert success"); + } + }); + }); +} +``` + +## 使用证书链校验器操作 + +**场景说明** + +使用证书链校验器操作中,典型的场景有: + +1. 证书链校验。 + +**接口及参数说明** + +详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)。 + +以上场景涉及的常用接口如下表所示: + +| 实例名 | 接口名 | 描述 | +| ------------------ | ------------------------------------------------------------ | -------------------------------- | +| cryptoFramework | createCertChainValidator(algorithm :string) : CertChainValidator | 使用指定算法生成证书链校验器对象 | +| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback) : void | 使用callback方式校验证书链 | +| CertChainValidator | validate(certChain : CertChainData) : Promise | 使用promise方式校验证书链 | +| CertChainValidator | algorithm : string | 证书链校验器算法名称 | + +**开发步骤** + +示例:创建证书链校验器对象,并对证书链数据进行校验(场景1) + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 一级证书数据,此处仅示例,业务需自行设置真实数据 +let caCertData = "-----BEGIN CERTIFICATE-----\n" ++ "...\n" ++ "...\n" ++ "...\n" ++ "-----END CERTIFICATE-----\n"; + +// 二级证书数据,此处仅示例,业务需自行设置真实数据 +let secondCaCertData = "-----BEGIN CERTIFICATE-----\n" ++ "...\n" ++ "...\n" ++ "...\n" ++ "-----END CERTIFICATE-----\n"; + +// string转Uint8Array +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; i++) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// 证书链校验器示例:此示例中以校验二级证书链为例,业务需根据场景自行修改 +function certChainValidatorSample() { + // 证书链校验器算法,当前仅支持PKIX + let algorithm = "PKIX"; + + // 创建证书链校验器对象 + let validator = cryptoFramework.createCertChainValidator(algorithm); + + // 一级证书数据 + let uint8ArrayOfCaCertData = stringToUint8Array(caCertData); + + // 一级证书数据长度 + let uint8ArrayOfCaCertDataLen = new Uint8Array(new Uint16Array([uint8ArrayOfCaCertData.byteLength]).buffer); + + // 二级证书数据 + let uint8ArrayOf2ndCaCertData = stringToUint8Array(secondCaCertData); + + // 二级证书数据长度 + let uint8ArrayOf2ndCaCertDataLen = new Uint8Array(new Uint16Array([uint8ArrayOf2ndCaCertData.byteLength]).buffer); + + // 证书链二进制数据:二级证书数据长度+二级证书数据+一级证书数据长度+一级证书数据(L-V格式) + let encodingData = new Uint8Array(uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length + + uint8ArrayOfCaCertDataLen.length + uint8ArrayOfCaCertData.length); + for (var i = 0; i < uint8ArrayOf2ndCaCertDataLen.length; i++) { + encodingData[i] = uint8ArrayOf2ndCaCertDataLen[i]; + } + for (var i = 0; i < uint8ArrayOf2ndCaCertData.length; i++) { + encodingData[uint8ArrayOf2ndCaCertDataLen.length + i] = uint8ArrayOf2ndCaCertData[i]; + } + for (var i = 0; i < uint8ArrayOfCaCertDataLen.length; i++) { + encodingData[uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length + i] = uint8ArrayOfCaCertDataLen[i]; + } + for (var i = 0; i < uint8ArrayOfCaCertData.length; i++) { + encodingData[uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length + + uint8ArrayOfCaCertDataLen.length + i] = uint8ArrayOfCaCertData[i]; + } + + let certChainData = { + // Uint8Array类型:L-V格式(证书数据长度-证书数据) + data: encodingData, + // 证书数量,此示例中为2 + count: 2, + // 证书格式:支持PEM和DER,此例中对应PEM + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM + }; + + // 校验证书链 + validator.validate(certChainData, function (err, data) { + if (err != null) { + // 证书链校验失败 + Console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 证书链校验成功 + Console.log("validate success"); + } + }); +} +``` + +## 使用被吊销证书操作 + +**场景说明** + +使用被吊销证书操作中,典型的场景有: + +1. 获取被吊销证书对象。 +2. 获取被吊销证书信息,比如:序列号、证书颁发者、证书吊销日期。 +3. 获取被吊销证书对象的序列化数据。 + +**接口及参数说明** + +详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)。 + +以上场景涉及的常用接口如下表所示: + +| 实例名 | 接口名 | 描述 | +| ------------ | ----------------------------------------------------------- | ------------------------------------------ | +| X509CrlEntry | getEncoded(callback : AsyncCallback) : void; | 使用callback方式获取被吊销证书的序列化数据 | +| X509CrlEntry | getEncoded() : Promise; | 使用promise方式获取被吊销证书的序列化数据 | +| X509CrlEntry | getSerialNumber() : number; | 获取被吊销证书的序列号 | +| X509CrlEntry | getCertIssuer(callback : AsyncCallback) : void; | 使用callback方式获取被吊销证书颁发者 | +| X509CrlEntry | getCertIssuer() : Promise; | 使用promise方式获取被吊销证书颁发者 | +| X509CrlEntry | getRevocationDate(callback : AsyncCallback) : void; | 使用callback方式获取被吊销证书的吊销日期 | +| X509CrlEntry | getRevocationDate() : Promise; | 使用promise方式获取被吊销证书的吊销日期 | + +**开发步骤** + +示例:获取被吊销证书对象,并调用对象方法(包含场景1-3) + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// 被吊销证书示例 +function crlEntrySample() { + // 业务需自行通过cryptoFramework的createX509Crl接口创建X509Crl对象,此处省略 + let x509Crl = null; + + // 获取被吊销证书对象,业务需根据场景调用X509Crl的接口获取,此示例使用getRevokedCert获取 + let serialNumber = 1000; + x509Crl.getRevokedCert(serialNumber, function (err, crlEntry) { + if (err != null) { + // 获取被吊销证书对象失败 + Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); + return; + } + // 获取被吊销证书对象成功 + Console.log("getRevokedCert success"); + + // 获取被吊销证书的序列号 + let serialNumber = crlEntry.getSerialNumber(); + + // 获取被吊销证书的吊销日期 + crlEntry.getRevocationDate(function (err, date) { + if (err != null) { + // 获取吊销日期失败 + Console.log("getRevocationDate failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取吊销日期成功 + Console.log("getRevocationDate success, date is: " + date); + } + }); + + // 获取被吊销证书对象的序列化数据 + crlEntry.getEncoded(function (err, data) { + if (err != null) { + // 获取序列化数据失败 + Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // 获取序列化数据成功 + Console.log("getEncoded success"); + } + }); + }); +} +``` + 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/Readme-CN.md b/zh-cn/application-dev/task-management/Readme-CN.md index 216d2ed2bdf4c7188a26b1449cc0d209861ec8db..994e21697c55f18fd58df906939975cca4f694d8 100644 --- a/zh-cn/application-dev/task-management/Readme-CN.md +++ b/zh-cn/application-dev/task-management/Readme-CN.md @@ -6,4 +6,8 @@ - 延迟任务调度 - [延迟任务调度概述](work-scheduler-overview.md) - - [延迟任务调度开发指导](work-scheduler-dev-guide.md) \ No newline at end of file + - [延迟任务调度开发指导](work-scheduler-dev-guide.md) + +- 后台代理提醒 + - [后台代理提醒开发概述](background-agent-scheduled-reminder-overview.md) + - [后台代理提醒开发指导](background-agent-scheduled-reminder-guide.md) \ No newline at end of file diff --git a/zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md similarity index 94% rename from zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md rename to zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md index ca596efaaa2537e895135f474c1ab6bc2bc71619..f442fa9914b821e1009fc3452a41e531d2c518a0 100644 --- a/zh-cn/application-dev/notification/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/notification/background-agent-scheduled-reminder-overview.md b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md similarity index 100% rename from zh-cn/application-dev/notification/background-agent-scheduled-reminder-overview.md rename to zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md 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 139043496961c6311577bcf561ec59a50010c14c..21d5bb76c6a986704252e9cc3cb577d9d159c75a 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 @@ -654,4 +654,4 @@ try { 基于后台任务管理,有以下相关实例可供参考: -- [`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 1e7ddc1d47d8e85fd759a358d09bfd45add69e5a..3d3866f2c3b1904dc896cf043203677c3e76011e 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 @@ -234,4 +234,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 3d809b82f2c6fbc107a710376dc63b3fd2800b60..842f41437ad61473148e93a21923e70e045c1052 100644 --- a/zh-cn/application-dev/ui/arkui-overview.md +++ b/zh-cn/application-dev/ui/arkui-overview.md @@ -1,42 +1,60 @@ # 方舟开发框架概述 -## 框架介绍 - -方舟开发框架(简称:ArkUI),是一套UI开发框架,提供开发者进行应用UI开发时所必需的能力。 - +方舟开发框架(简称:ArkUI),是一套构建OpenHarmony应用界面的UI开发框架,它提供了极简的UI语法与包括UI组件、动画机制、事件交互等在内的UI开发基础设施,以满足应用开发者的可视化界面开发需求。 ## 基本概念 -- 组件:组件是界面搭建与显示的最小单位。开发者通过多种组件的组合,构建出满足自身应用诉求的完整界面。 - -- 页面:page页面是方舟开发框架最小的调度分割单位。开发者可以将应用设计为多个功能页面,每个页面进行单独的文件管理,并通过路由API实现页面的调度管理,以实现应用内功能的解耦。 +- **组件:** 组件是界面搭建与显示的最小单位。开发者通过多种组件的组合,构建出满足自身应用诉求的完整界面。 +- **页面:** page页面是方舟开发框架最小的调度分割单位。开发者可以将应用设计为多个功能页面,每个页面进行单独的文件管理,并通过[页面路由](../reference/apis/js-apis-router.md)API完成页面间的调度管理,以实现应用内功能的解耦。 ## 主要特征 -- UI组件:方舟开发框架不仅提供了多种基础组件, 例如文本、图片、按钮等 ,也提供了支持视频播放能力的媒体组件。并且针对不同类型设备进行了组件设计,提供了组件在不同平台上的样式适配能力,此种组件称为“多态组件”。 +- **UI组件:** 方舟开发框架内置了丰富的多态组件,包括文本、图片、按钮等基础组件,可包含一个或多个子组件的容器组件,满足开发者自定义绘图需求的绘制组件,以及提供视频播放能力的媒体组件等。其中“多态”是指组件针对不同类型设备进行了设计,提供了在不同平台上的样式适配能力。 -- 布局:UI界面设计离不开布局的参与。方舟开发框架提供了多种布局方式,不仅保留了经典的弹性布局能力,也提供了列表、宫格、栅格布局和适应多分辨率场景开发的原子布局能力。 +- **布局:** UI界面设计离不开布局的参与。方舟开发框架提供了多种布局方式,除了基础的线性布局、弹性布局外,也提供了相对复杂的列表、宫格、栅格布局,以及自适应多分辨率场景开发的原子布局能力。 -- 动画:方舟开发框架对于UI界面的美化,除了组件内置动画效果外,也提供了属性动画、转场动画和自定义动画能力。 +- **动画:** 动画是UI界面的重要元素之一,优秀的动画设计能够极大地提升用户体验,方舟开发框架提供了丰富的动画能力,除了组件内置动画效果外,还包括属性动画、自定义转场动画以及动画API等。 -- 绘制:方舟开发框架提供了多种绘制能力,以满足开发者绘制自定义形状的需求,支持图形绘制、颜色填充、文本绘制、图片绘制等。 +- **绘制:** 方舟开发框架提供了多种绘制能力,以满足开发者的自定义绘图需求,支持绘制形状、颜色填充、绘制文本、变形与裁剪、嵌入图片等。 -- 交互事件:方舟开发框架提供了多种交互能力,满足应用在不同平台通过不同输入设备均可正常进行UI交互响应,默认适配了触摸手势、遥控器、鼠标等输入操作,同时也提供事件通知能力。 +- **交互事件:** 方舟开发框架提供了多种交互能力,以满足应用在不同平台通过不同输入设备进行UI交互响应的需求,默认适配了触摸手势、遥控器按键输入、键鼠输入,同时提供了相应的事件回调以便开发者添加交互逻辑。 -- 平台API通道:方舟开发框架提供了API扩展机制,平台能力通过此种机制进行封装,提供风格统一的JS接口。 +- **平台API通道:** 方舟开发框架提供了API扩展机制,可通过该机制对平台能力进行封装,提供风格统一的JS接口。 -- 两种开发范式:方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于eTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。 +- **两种开发范式:** 方舟开发框架针对不同的应用场景以及不同技术背景的开发者提供了两种开发范式,分别是[基于ArkTS的声明式开发范式](./ui-ts-overview.md)(简称“声明式开发范式”)和[兼容JS的类Web开发范式](./ui-js-overview.md)(简称“类Web开发范式”)。 | 开发范式名称 | 简介 | 适用场景 | 适用人群 | | -------- | ---------------------------------------- | ---------------- | ------------------- | - | 声明式开发范式 | 采用TS语言并进行声明式UI语法扩展,从组件、动效和状态管理三个维度提供了UI绘制能力。UI开发更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。同时,选用有类型标注的TS语言,引入编译期的类型校验。 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | - | 类Web开发范式 | 采用经典的HML、CSS、JavaScript三段式开发方式。使用HML标签文件进行布局搭建,使用CSS文件进行样式描述,使用JavaScript文件进行逻辑处理。UI组件与数据之间通过单向数据绑定的方式建立关联,当数据发生变化时,UI界面自动触发更新。此种开发方式,更接近Web前端开发者的使用习惯,快速将已有的Web应用改造成方舟开发框架应用。 | 界面较为简单的中小型应用和卡片 | Web前端开发人员 | + | 声明式开发范式 | 采用基于TypeScript进行声明式UI语法扩展而来的[ArkTS语言](../quick-start/arkts-get-started.md),从组件、动画和状态管理三个维度提供了UI绘制能力。声明式开发范式更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。 | 复杂度较大、团队合作度较高的应用 | 移动系统应用开发人员、系统应用开发人员 | + | 类Web开发范式 | 采用经典的HML、CSS、JavaScript三段式开发方式,使用HML标签文件进行布局搭建,使用CSS文件进行样式描述,使用JavaScript文件进行逻辑处理。UI组件与数据之间通过单向数据绑定的方式建立关联,当数据发生变化时,UI界面自动触发刷新。该开发方式更接近Web前端开发者的使用习惯,便于快速将已有的Web应用改造成方舟开发框架应用。 | 界面较简单的中小型应用和卡片 | Web前端开发人员 | +## 框架结构 +![zh-cn_image_0000001183709904](figures/zh-cn_image_0000001183709904.png) -### 框架结构 +从上图可以看出,类Web开发范式与声明式开发范式的UI后端引擎和语言运行时是共用的,其中,UI后端引擎实现了方舟开发框架的六种基本能力。声明式开发范式无需JS Framework进行页面DOM管理,渲染更新链路更为精简,占用内存更少,因此更推荐开发者选用声明式开发范式来搭建应用UI界面。 + +## UI与Ability框架的关系 + +Ability也是OpenHarmony应用的重要组成部分,[Ability框架](../ability/ability-brief.md)包括FA模型与Stage模型两种模型。下表给出了Ability框架的两种模型分别与方舟开发框架的两种开发范式的关系。 + + **FA模型:** + + | 类型 | UI开发范式 | 说明 | + | -------- | --------------------------- | --------------------------- | + | 应用 | 类web开发范式 | UI开发语言:使用hml/css/js
业务入口:使用固定文件名app.ets(Page类型Ability)/service.ts(Service类型Ability)/data.ts(Data类型Ability)
业务逻辑语言:js/ts | + | | 声明式开发范式 | UI开发语言:ArkTS
业务入口:使用固定文件名app.ets(Page类型Ability)/service.ts(Service类型Ability)/data.ts(Data类型Ability)
业务逻辑语言:js/ts | + | 服务卡片 | 类web开发范式 | UI开发语言:卡片显示使用hml+css+json(action)
业务入口:form.ts
卡片业务逻辑语言:js/ts | + | | 声明式开发范式 | 当前不支持 | + + **Stage模型:** + + | 类型 | UI开发范式 | 说明 | + | -------- | --------------------------- | --------------------------- | + | 应用 | 类web开发范式 | 当前不支持 | + | | 声明式开发范式 | UI开发语言:ArkTS
业务入口:应用模型基于ohos.application.Ability/ExtensionAbility等派生
业务逻辑语言:ts | + | 服务卡片 | 类web开发范式 | UI开发语言:卡片显示使用hml+css+json(action)
业务入口:从FormExtensionAbility派生
业务逻辑语言:ts | + | | 声明式开发范式 | 当前不支持 | -![zh-cn_image_0000001183709904](figures/zh-cn_image_0000001183709904.png) -从上图可以看出,类Web开发范式与声明式开发范式的UI后端引擎和语言运行时是共用的,其中,UI后端引擎实现了方舟开发框架的六种基本能力。声明式开发范式无需JS Framework进行页面DOM管理,渲染更新链路更为精简,占用内存更少,因此更推荐开发者选用声明式开发范式来搭建应用UI界面。 \ No newline at end of file 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/contribute/OpenHarmony-security-test-guide.md b/zh-cn/contribute/OpenHarmony-security-test-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef9bd4f8bbce5ab95a5100098077b68b16ef5c8 --- /dev/null +++ b/zh-cn/contribute/OpenHarmony-security-test-guide.md @@ -0,0 +1,27 @@ +# OpenHarmony安全测试规范 +本文档主要参考业界安全测试标准和最佳实践,提供OpenHarmony安全测试规范,用于指导开发人员/测试人员进行安全测试。 + + + +## 安全编码测试 + +1、各模块依据[OpenHarmony安全编码规范](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-c-cpp-secure-coding-guide.md),进行代码安全检视。 + +2、使用安全编码扫描工具扫描测试,扫描告警结果清零。OpenHarmony代码门禁已集成安全编码扫描工具。 + + +## 安全设计验证 + +1、各模块依据[OpenHarmony安全设计规范](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-security-design-guide.md),结合业务完成安全设计自检验证。 + + + +## 安全测试工具扫描 + +1、针对高风险模块,开发人员需要依据[Fuzz测试框架](https://gitee.com/openharmony/test_developertest/tree/master/libs/fuzzlib)开发灰白盒Fuzz测试套,并完成灰白盒Fuzz测试。 + +2、针对暴露用户态接口进行黑盒Fuzz,包括但不限于系统服务接口、内核驱动接口、socket网络接口。 + +3、依据[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md),使用编译选项扫描工具检查文件编译选项开启情况。 + +4、针对开源组件使用业界漏洞扫描工具扫描,开源组件漏洞均已按照社区漏洞管理流程修复。 \ No newline at end of file diff --git a/zh-cn/device-dev/device-test/developer_test.md b/zh-cn/device-dev/device-test/developer_test.md new file mode 100644 index 0000000000000000000000000000000000000000..05f860d7e9dc7420a75d0f9daa8fb378979fe9ee --- /dev/null +++ b/zh-cn/device-dev/device-test/developer_test.md @@ -0,0 +1,851 @@ +# 开发自测试执行框架使用指南 + + +## 概述 + +OpenHarmony为开发者提供了一套全面的开发自测试框架developer_test,作为OpenHarmony测试工具集的一部分,提供给开发者自测试使用。开发者可根据测试需求开发相关测试用例,开发阶段提前发现缺陷,大幅提高代码质量。 + +本文从基础环境构建,用例开发,编译以及执行等方面介绍OpenHarmony开发自测试执行框架如何运行和使用。 + + +### 简介 + +OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速的验证修改代码的功能的正确性,而系统中已经存在了大量的已有功能的自动化测试用例,比如TDD用例或XTS用例等。开发者自测试执行框架目的就是为了提升开发者的自测试执行效率,方便开发人员可以快速便捷的执行指定的自动化测试用例,将测试活动左移到开发阶段。 + + +### 约束与限制 + +- 框架使用时必须提前连接OpenHarmony设备方可执行测试用例。 + + +## 环境准备 + +开发自测试框架依赖于python运行环境,python版本为3.8.X,在使用测试框架之前可参阅以下方式进行配置。 + + - [环境配置](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-testguide-test.md#%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE) + - [源码获取](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md) + + +## 编写测试用例 + +本测试框架支持多种类型测试,针对不同测试类型提供了不同的用例编写模板以供参考。_ + +**TDD测试(C++)** + +用例源文件命名规范 + +测试用例源文件名称和测试套内容保持一致,文件命名采用全小写+下划线方式命名,以test结尾,具体格式为:[功能]_[子功能]_test,子功能支持向下细分。 +示例: +``` +calculator_sub_test.cpp +``` + +用例示例 +``` +/* + * Copyright (c) 2021 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "calculator.h" +#include + +using namespace testing::ext; + +class CalculatorSubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CalculatorSubTest::SetUpTestCase(void) +{ + // input testsuit setup step,setup invoked before all testcases +} + +void CalculatorSubTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void CalculatorSubTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases +} + +void CalculatorSubTest::TearDown(void) +{ + // input testcase teardown step,teardown invoked after each testcases +} + +/** + * @tc.name: integer_sub_001 + * @tc.desc: Verify the sub function. + * @tc.type: FUNC + * @tc.require: issueNumber + */ +HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) +{ + // step 1:调用函数获取结果 + int actual = Sub(4,0); + + // Step 2:使用断言比较预期与实际结果 + EXPECT_EQ(4, actual); +} +``` +详细内容介绍: + +1.添加测试用例文件头注释信息 + +``` +/* + * Copyright (c) 2021 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +``` + +2.引用测试框架头文件和命名空间 + +``` +#include + +using namespace testing::ext; +``` + +3.添加被测试类的头文件 + +``` +#include "calculator.h" +``` + +4.定义测试套(测试类) + +``` +class CalculatorSubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CalculatorSubTest::SetUpTestCase(void) +{ + // input testsuit setup step,setup invoked before all testcases +} + +void CalculatorSubTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void CalculatorSubTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases +} + +void CalculatorSubTest::TearDown(void) +{ + // input testcase teardown step,teardown invoked after each testcases +} +``` +> **注意:** 在定义测试套时,测试套名称应与编译目标保持一致,采用大驼峰风格。 + +5.测试用例实现,包含用例注释和逻辑实现 + +``` +/** + * @tc.name: integer_sub_001 + * @tc.desc: Verify the sub function. + * @tc.type: FUNC + * @tc.require: issueNumber + */ +HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) +{ + //step 1:调用函数获取结果 + int actual = Sub(4,0); + + //Step 2:使用断言比较预期与实际结果 + EXPECT_EQ(4, actual); +} +``` +> **注意:** @tc.require: 格式必须以AR/SR或issue开头: 如:issueI56WJ7 + +在编写用例时,我们提供了三种用例模板供您选择。 + +| 类型 | 描述 | +| --------------- | ------------------------------------------------ | +| HWTEST(A,B,C) | 用例执行不依赖Setup&Teardown时,可选取 | +| HWTEST_F(A,B,C) | 用例执行(不含参数)依赖于Setup&Teardown时,可选取 | +| HWTEST_P(A,B,C) | 用例执行(含参数)依赖于Set&Teardown时,可选取 | + +其中,参数A,B,C的含义如下: + +- 参数A为测试套名。 + +- 参数B为测试用例名,其命名必须遵循[功能点]_[编号]的格式,编号为3位数字,从001开始。 + +- 参数C为测试用例等级,具体分为门禁level0 以及非门禁level1-level4共五个等级,其中非门禁level1-level4等级的具体选取规则为:测试用例功能越重要,level等级越低。 + + +**注意:** + +- 测试用例的预期结果必须有对应的断言。 + +- 测试用例必须填写用例等级。 + +- 测试体建议按照模板分步实现。 + +- 用例描述信息按照标准格式@tc.xxx value书写,注释信息必须包含用例名称,用例描述,用例类型,需求编号四项。其中用例测试类型@tc.type参数的选取,可参考下表。 + + +| 测试类型名称 | 类型编码 | +| ------------ | -------- | +| 功能测试 | FUNC | +| 性能测试 | PERF | +| 可靠性测试 | RELI | +| 安全测试 | SECU | +| 模糊测试 | FUZZ | + +**TDD测试(JS)** + +- 用例源文件命名规范 + + +测试用例原文件名称采用大驼峰风格,以TEST结尾,具体格式为:[功能][子功能]TEST,子功能支持向下细分。 +示例: +``` +AppInfoTest.js +``` + +- 用例示例 + +``` +/* + * Copyright (C) 2021 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import app from '@system.app' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("AppInfoTest", function () { + beforeAll(function() { + // input testsuit setup step,setup invoked before all testcases + console.info('beforeAll caled') + }) + + afterAll(function() { + // input testsuit teardown step,teardown invoked after all testcases + console.info('afterAll caled') + }) + + beforeEach(function() { + // input testcase setup step,setup invoked before each testcases + console.info('beforeEach caled') + }) + + afterEach(function() { + // input testcase teardown step,teardown invoked after each testcases + console.info('afterEach caled') + }) + + /* + * @tc.name:appInfoTest001 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: issueNumber + */ + it("appInfoTest001", 0, function () { + //step 1:调用函数获取结果 + var info = app.getInfo() + + //Step 2:使用断言比较预期与实际结果 + expect(info != null).assertEqual(true) + }) +}) +``` +详细内容介绍: +1. 添加测试用例文件头注释信息 + ``` + /* + * Copyright (C) 2021 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + ``` +2. 导入被测api和jsunit测试库 + ``` + import app from '@system.app' + + import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + ``` +3. 定义测试套(测试类) + ``` + describe("AppInfoTest", function () { + beforeAll(function() { + // input testsuit setup step,setup invoked before all testcases + console.info('beforeAll caled') + }) + + afterAll(function() { + // input testsuit teardown step,teardown invoked after all testcases + console.info('afterAll caled') + }) + + beforeEach(function() { + // input testcase setup step,setup invoked before each testcases + console.info('beforeEach caled') + }) + + afterEach(function() { + // input testcase teardown step,teardown invoked after each testcases + console.info('afterEach caled') + }) + ``` +4. 测试用例实现 + ``` + /* + * @tc.name:appInfoTest001 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: issueNumber + */ + it("appInfoTest001", 0, function () { + //step 1:调用函数获取结果 + var info = app.getInfo() + + //Step 2:使用断言比较预期与实际结果 + expect(info != null).assertEqual(true) + }) + ``` + > **注意:** @tc.require: 格式必须以AR/SR或issue开头: 如:issueI56WJ7 + +**Fuzz测试** + +[Fuzz用例编写规范](https://gitee.com/openharmony/test_developertest/blob/master/libs/fuzzlib/README_zh.md) + + +**Benchmark测试** + +[Benchmark用例编写规范](https://gitee.com/openharmony/test_developertest/blob/master/libs/benchmark/README_zh.md)_ + +## 编译测试用例 + +根据测试用例目录规划,当执行某一用例时,测试框架会根据编译文件逐层查找,最终找到所需用例进行编译。下面通过不同示例来讲解gn文件如何编写。 + +**TDD测试** + +针对不同语言,下面提供不同的编译模板以供参考。 + +- **C++用例编译配置示例** + +``` +# Copyright (c) 2021 XXXX Device Co., Ltd. + +import("//build/test.gni") + +module_output_path = "developertest/calculator" + +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ "../../../include" ] +} + +ohos_unittest("CalculatorSubTest") { + module_out_path = module_output_path + + sources = [ + "../../../include/calculator.h", + "../../../src/calculator.cpp", + ] + + sources += [ "calculator_sub_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ "//third_party/googletest:gtest_main" ] +} + +group("unittest") { + testonly = true + deps = [":CalculatorSubTest"] +} +``` +详细内容如下: + +1. 添加文件头注释信息 + ``` + # Copyright (c) 2021 XXXX Device Co., Ltd. + ``` +2. 导入编译模板文件 + ``` + import("//build/test.gni") + ``` +3. 指定文件输出路径 + ``` + module_output_path = "developertest/calculator" + ``` + > **说明:** 此处输出路径为部件/模块名。 + +4. 配置依赖包含目录 + + ``` + config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ "../../../include" ] + } + ``` + > **说明:** 一般在此处对相关配置进行设置,在测试用例编译脚本中可直接引用。 + +5. 指定测试用例编译目标输出的文件名称 + + ``` + ohos_unittest("CalculatorSubTest") { + } + ``` +6. 编写具体的测试用例编译脚本(添加需要参与编译的源文件、配置和依赖) + ``` + ohos_unittest("CalculatorSubTest") { + module_out_path = module_output_path + sources = [ + "../../../include/calculator.h", + "../../../src/calculator.cpp", + "../../../test/calculator_sub_test.cpp" + ] + sources += [ "calculator_sub_test.cpp" ] + configs = [ ":module_private_config" ] + deps = [ "//third_party/googletest:gtest_main" ] + } + ``` + + > **说明:根据测试类型的不同,在具体编写过程中可选择不同的测试类型:** + > - ohos_unittest:单元测试 + > - ohos_moduletest:模块测试 + > - ohos_systemtest:系统测试 + > - ohos_performancetest:性能测试 + > - ohos_securitytest:安全测试 + > - ohos_reliabilitytest:可靠性测试 + > - ohos_distributedtest:分布式测试 + +7. 对目标测试用例文件进行条件分组 + + ``` + group("unittest") { + testonly = true + deps = [":CalculatorSubTest"] + } + ``` + > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 + +- **JavaScript用例编译配置示例** + +``` +# Copyright (C) 2021 XXXX Device Co., Ltd. + +import("//build/test.gni") + +module_output_path = "developertest/app_info" + +ohos_js_unittest("GetAppInfoJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + +group("unittest") { + testonly = true + deps = [ ":GetAppInfoJsTest" ] +} +``` + +详细内容如下: + +1.添加文件头注释信息 + +``` +# Copyright (C) 2021 XXXX Device Co., Ltd. +``` + +2.导入编译模板文件 + +``` +import("//build/test.gni") +``` + +3.指定文件输出路径 + +``` +module_output_path = "developertest/app_info" +``` +> **说明:** 此处输出路径为部件/模块名。 + +4.指定测试用例编译目标输出的文件名称 + +``` +ohos_js_unittest("GetAppInfoJsTest") { +} +``` +> **说明:** +> - 使用模板ohos_js_unittest定义js测试套,注意与C++用例区分。 +> - js测试套编译输出文件为hap类型,hap名为此处定义的测试套名,测试套名称必须以JsTest结尾。 + +5.指定hap包配置文件config.json和签名文件,两个配置为必选项 + +``` +ohos_js_unittest("GetAppInfoJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} +``` + config.json为hap编译所需配置文件,需要开发者根据被测sdk版本配置“target”项,其余项可默认,具体如下所示: + +``` +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 // 根据被测sdk版本进行修改,此例为sdk5 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } + } +``` + +6.对目标测试用例文件进行条件分组 + +``` +group("unittest") { + testonly = true + deps = [ ":GetAppInfoJsTest" ] +} +``` +> **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 + +**Fuzz测试** + +[Fuzz编译文件编写规范](https://gitee.com/openharmony/test_developertest/blob/master/libs/fuzzlib/README_zh.md) + +**Benchmark测试** + +[Benchmark编译文件编写规范](https://gitee.com/openharmony/test_developertest/blob/master/libs/benchmark/README_zh.md) + + +**编译入口配置文件ohos.build** + +当完成用例编译配置文件编写后,需要进一步编写部件编译配置文件,以关联到具体的测试用例。 +``` +"partA": { + "module_list": [ + + ], + "inner_list": [ + + ], + "system_kits": [ + + ], + "test_list": [ //配置模块calculator下的test + "//system/subsystem/partA/calculator/test:unittest", + "//system/subsystem/partA/calculator/test:fuzztest", + "//system/subsystem/partA/calculator/test:benchmarktest" + } +``` +> **说明:** test_list中配置的是对应模块的测试用例。 + +## 测试资源配置 + +试依赖资源主要包括测试用例在执行过程中需要的图片文件,视频文件、第三方库等对外的文件资源。 + +依赖资源文件配置步骤如下: + +1.在部件的test目录下创建resource目录,在resource目录下创建对应的模块,在模块目录中存放该模块所需要的资源文件 + +2.在resource目录下对应的模块目录中创建一个ohos_test.xml文件,文件内容格式如下: + +``` + + + + + + + +``` + +3.在测试用例的编译配置文件中定义resource_config_file进行指引,用来指定对应的资源文件ohos_test.xml + +``` +ohos_unittest("CalculatorSubTest") { + resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" +} +``` +>**说明:** +>- target_name: 测试套的名称,定义在测试目录的BUILD.gn中。preparer: 表示该测试套执行前执行的动作。 +>- src="res": 表示测试资源位于test目录下的resource目录下,src="out":表示位于out/release/$(部件)目录下。 + +## 执行测试用例 + +### 配置文件 + +在执行测试用例之前,针对用例使用设备的不同,需要对相应配置进行修改,修改完成即可执行测试用例。 + +#### user_config.xml配置 +``` + + + + false + + false + + true + + + + + + + + + + + + + + + + + cmd + 115200 + 8 + 1 + 1 + + + + + + + + + + + + + + + + + + +``` +>**说明:** 在执行测试用例之前,若使用HDC连接设备,用例仅需配置设备IP和端口号即可,其余信息均默认不修改。 + +### 执行命令说明 + +1. 启动测试框架 + ``` + start.bat + ``` +2. 选择产品形态 + + 进入测试框架,系统会自动提示您选择产品形态,请根据实际的开发板进行选择。 + + 如需手动添加,请在config/framework_config.xml的\标签内增加产品项。 + +3. 执行测试用例 + + 当选择完产品形态,可参考如下指令执行测试用例。 + ``` + run -t UT -ts CalculatorSubTest -tc interger_sub_00l + ``` + 执行命令参数说明: + ``` + -t [TESTTYPE]: 指定测试用例类型,有UT,MST,ST,PERF,FUZZ,BENCHMARK等。(必选参数) + -tp [TESTPART]: 指定部件,可独立使用。 + -tm [TESTMODULE]: 指定模块,不可独立使用,需结合-tp指定上级部件使用。 + -ts [TESTSUITE]: 指定测试套,可独立使用。 + -tc [TESTCASE]: 指定测试用例,不可独立使用,需结合-ts指定上级测试套使用。 + -h : 帮助命令。 + +#### Windows环境执行 + +由于Windows环境下无法实现用例编译,因此执行用例前需要在Linux环境下进行用例编译,用例编译命令: +``` +./build.sh --product-name {product_name} --build-target make_test +``` + +>说明: +>- product-name:指定编译产品名称。 +>- build-target:指定所需编译用例,make_test表示指定全部用例,实际开发中可指定特定用例。 + +编译完成后,测试用例将自动保存在out/ohos-arm-release/packages/phone/tests目录下。 + +##### 搭建执行环境 +1. 在Windows环境创建测试框架目录Test,并在此目录下创建testcase目录 + +2. 从Linux环境拷贝测试框架developertest和xdevice到创建的Test目录下,拷贝编译好的测试用例到testcase目录下 + + >**说明:** 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 + +3. 修改user_config.xml + ``` + + + false + + + + D:\Test\testcase\tests + + ``` + >**说明:** ``标签表示是否需要编译用例;``标签表示测试用例查找路径。 + +#### Linux环境执行 + +如是直接连接Linux机器,则可直接使用上面的执行命令执行命令 + +##### 远程端口映射 +为支持Linux远程服务器以及Linux虚拟机两种环境下执行测试用例,需要对端口进行远程映射,以实现与设备的数据通路连接。具体操作如下: +1. HDC Server指令: + ``` + hdc_std kill + hdc_std -m -s 0.0.0.0:8710 + ``` + >**说明:** IP和端口号为默认值。 + +2. HDC Client指令: + ``` + hdc_std -s xx.xx.xx.xx:8710 list targets + ``` + >**说明:** 此处IP填写设备侧IP地址。 + +## 查看测试结果 + +### 测试报告日志 + +当执行完测试指令,控制台会自动生成测试结果,若需要详细测试报告您可在相应的数据文档中进行查找。 + +### 测试结果 +测试结果输出根路径如下: +``` +test/developertest/reports/xxxx_xx_xx_xx_xx_xx +``` +>**说明:** 测试报告文件目录将自动生成。 + +该目录中包含以下几类结果: +| 类型 | 描述 | +| ------------------------------------ | ------------------ | +| result/ | 测试用例格式化结果 | +| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | 测试用例日志 | +| summary_report.html | 测试报告汇总 | +| details_report.html | 测试报告详情 | + +### 测试框架日志 +``` +reports/platform_log_xxxx_xx_xx_xx_xx_xx.log +``` + +### 最新测试报告 +``` +reports/latest +``` 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/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index 10f14510e83b69dbad815992ca986139bb87df16..d243354b9c95f462dcddd8fcb6ef7acd396b62d9 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -65,6 +65,7 @@ - [虚拟文件系统](kernel-small-bundles-fs-virtual.md) - [支持的文件系统](kernel-small-bundles-fs-support.md) - [适配新的文件系统](kernel-small-bundles-fs-new.md) + - [Plimitsfs文件系统](kernel-small-plimits.md) - 调测与工具 - Shell - [Shell介绍](kernel-small-debug-shell-overview.md) diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image_0000002324.png b/zh-cn/device-dev/kernel/figures/zh-cn_image_0000002324.png new file mode 100644 index 0000000000000000000000000000000000000000..bb35a8ccde16464e275917644fb5066b2706bbdb Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/zh-cn_image_0000002324.png differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232425.png b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232425.png new file mode 100644 index 0000000000000000000000000000000000000000..8239b823f6d02fe6b9459b319c9f1260bbbfb789 Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232425.png differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232426.png b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232426.png new file mode 100644 index 0000000000000000000000000000000000000000..fd8550c59b39a3c98a225060e93b2316e7c45b96 Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232426.png differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232428.png b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232428.png new file mode 100644 index 0000000000000000000000000000000000000000..7c2ecfd6e8c1f0d84b9e9cb97efa29af98859d0b Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/zh-cn_image_000000232428.png differ diff --git a/zh-cn/device-dev/kernel/kernel-small-plimits.md b/zh-cn/device-dev/kernel/kernel-small-plimits.md new file mode 100644 index 0000000000000000000000000000000000000000..7472c723e125f842df01088fddf2ff3a4b7f94d9 --- /dev/null +++ b/zh-cn/device-dev/kernel/kernel-small-plimits.md @@ -0,0 +1,331 @@ +# 容器配额(plimits) + +## 简介 + +面对进程越来越多,应用环境越来越复杂的状况,需要对容器做限制,若不做限制,会发生资源浪费、争夺等。容器配额plimits(Process Limits)是内核提供的一种可以限制单个进程或者多个进程所使用资源的机制,可以对cpu,内存等资源实现精细化控制。plimits的接口通过plimitsfs的伪文件系统提供。通过操作文件对进程及进程资源进行分组管理,通过配置plimits组内限制器Plimiter限制进程组的memory、sched等资源的使用。 + +## 基本概念 + +- plimits:内核的一个特性,用于限制、记录和隔离一组进程的资源使用。 +- plimitsfs:plimits文件系统,向用户提供操作接口,实现plimits的创建,删除。向用户展示plimits的层级等。 +- plimiter:资源限制器的总称,一个子系统代表一类资源限制器,包含memory限制器、pids限制器、sched限制器。 +- sched限制器:限制plimits组内的所有进程,在时间周期内占用的cpu时间。 +- memory限制器:限制plimits组内所有进程的内存使用总和。 +- pids限制器:限制plimits组内能挂载的最大进程数。 + +## 运行机制 + +plimitsfs文件系统,在系统初始化阶段,初始化plimits目录挂载至proc目录下: + +``` +├─proc +│ ├─plimits +│ │ ├─plimits.plimiter_add +│ │ ├─plimits.plimiter_delete +│ │ ├─plimits.procs +│ │ ├─plimits.limiters +│ │ ├─pids.max +│ │ ├─sched.period +│ │ ├─sched.quota +│ │ ├─sched.stat +│ │ ├─memory.failcnt +│ │ ├─memory.limit +│ │ ├─memory.peak +│ │ ├─memory.usage +│ │ ├─memory.oom_ctrl +│ │ └─memory.stat +``` + +1. plimits分组: + + **图1** plimits创建/删除 + + ![zh-cn_image_0000002324](figures/zh-cn_image_0000002324.png) + +2. sched限制器: + + **图2** sched限制器配置 + + ![zh-cn_image_000000252628](figures/zh-cn_image_000000232425.png) + +3. memory限制器: + + **图3** memory限制器配置 + + ![zh-cn_image_000000232426](figures/zh-cn_image_000000232426.png) + +4. pids限制器: + + **图4** Pids限制器配置 + + ![zh-cn_image_000000232428](figures/zh-cn_image_000000232428.png) + + +## 开发指导 + + +### 接口说明 + +LiteOS-A的plimits根目录在/proc/plimits下,其下的所有文件只有只读权限,不允许写操作。限制器文件设定值默认为最大值,通过读文件,可查看组内进程资源状态。 +通过mkdir创建plimitsA目录完成对进程资源分组,进而操作资源的分配限制。创建的plimitsA目录继承其父plimits目录。 + +1. plimitsA文件目录见下表: + + |
权限
| 大小 | 用户 | 用户组 | 文件名 | 文件描述 | + | --------- | ---- | ---- | ------ | ---------------------- | --------- | + |-r--r--r-- | 0 | u:0 | g:0 | sched.stat | 每个线程上周期内使用的时间片信息,方便测试验证使用 | + |-rw-r--r-- | 0 | u:0 | g:0 | sched.quota | 组内所有进程在周期内使用时间片总和,单位:ns | + |-rw-r--r-- | 0 | u:0 | g:0 | sched.period | 时间片统计周期,单位:ns | + |-r--r--r-- | 0 | u:0 | g:0 | memory.stat | 统计内存使用的信息,单位:字节 | + |-r--r--r-- | 0 | u:0 | g:0 | memory.usage | 已使用内存份额,单位:字节 | + |-r--r--r-- | 0 | u:0 | g:0 | memory.peak | 内存历史使用峰值,单位:字节 | + |-rw-r--r-- | 0 | u:0 | g:0 | memory.limit | 内存使用限额,单位:字节 | + |-r--r--r-- | 0 | u:0 | g:0 | memory.failcnt | 记录超过限额内存分配失败的次数,单位:次 | + |-rw-r--r-- | 0 | u:0 | g:0 | pids.max | 组内允许挂载进程的最大数,单位:个 | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.procs | 组内挂载的所有进程 | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.limiter_delete | 根据写入的限制器名称,删除限制器 | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.limiter_add | 根据写入的限制器名称,添加限制器 | + |-r--r--r-- | 0 | u:0 | g:0 | plimits.limiters | 查看组内限制器 | + + 在/proc/plimits/下创建的plimitsA目录下文件均可读部分可写,通过write对plimitsA子目录中写入内容,完成对进程资源分配与限制。 + - 对文件sched.quota写入时间,单位ns,可限制组内所有进程使用cpu的时间 + - 对文件sched.period写入时间,单位ns,可设置组内统计的时间周期 + - 对文件memory.limit写入内存,单位字节,可限制组内允许使用的内存制 + - 对文件pids.max写入十进制数字,可限制组内允许挂载的进程个数 + - 对文件plimits.procs写入Pid,可将进程挂到不同的plimits组 + - 通过read读不同的文件,可查看组内资源配置使用状况 + +2. 删除plimitsA组: + + 首先对/proc/plimits/plimitsA/plimits.limiter_delete文件依次写入字段“sched”、“memory”、“pids”删除限制器,才能使用rmdir删除plimitsA。 + + | 权限 | 大小 | 用户 | 用户组 | 文件名 | + | --------- | ------- | ------ | ------ | ----------------------- | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.procs | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.limiter_delete | + |-rw-r--r-- | 0 | u:0 | g:0 | plimits.limiter_add | + |-r--r--r-- | 0 | u:0 | g:0 | plimits.limiters | + +### 开发流程 + +plimits文件系统的主要开发流程包括创建新的plimitsA,将pid号写入/plimitsA/plimits.procs,对进程资源分组;按照字节大小写文件/plimitsA/memory.limit文件,限制plimitsA组内能使用的最大内存;对文件/plimitsA/pids.max写入十进制数字限制plimitsA组内所能挂载的进程数等;通过配置plimitsA组内限制器文件,对相应的资源进行分配和限制。亦可删除plimitsA,不限制资源的使用。 + +### 编程实例 + +编程示例主要是创建分组plimitsA,通过读写子目录内容,完成进程与进程资源的分组,对Plimits组内进程资源限制。 + +``` +#include +#include +#include +#include +#include +#include +#include + +#define LOS_OK 0 +#define LOS_NOK -1 + +int main () +{ + int ret; + ssize_t len; + int fd = -1; + //get main pid + int mainpid = getpid(); + char plimitsA[128] = "/proc/plimits/plimitsA"; + char plimitsAPids[128] = "/proc/plimits/plimitsA/pids.max"; + char plimitsAMemoryLimit[128] = "/proc/plimits/plimitsA/memory.limit"; + char plimitsAMemoryUsage[128] = "/proc/plimits/plimitsA/memory.usage"; + char plimitsAProcs[128] = "/proc/plimits/plimitsA/plimits.procs"; + char plimitsAAdd[128] = "/proc/plimits/plimitsA/plimits.limiter_add"; + char plimitsADelete[128] = "/proc/plimits/plimitsA/plimits.limiter_delete"; + char plimitsMem[128] = "/proc/plimits/memory.usage"; + char plimitsPid[128] = "/proc/plimits/plimits.procs"; + char *mem = NULL; + char writeBuf[128]; + char readBuf[128]; + + /* 查看根plimits组内进程 */ + memset(readBuf, 0, sizeof(readBuf)); + fd = open(plimitsPid, O_RDONLY); + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(readBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + close(fd); + printf("/proc/plimits组内进程:%s\n", readBuf); + + /* 查看根plimits组内内存使用 */ + memset(readBuf, 0, sizeof(readBuf)); + fd = open(plimitsMem, O_RDONLY); + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(readBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + close(fd); + printf("/proc/plimits组内已使用内存:%s\n", readBuf); + + + /* 创建plimitsA “/proc/plimits/plimitsA” */ + ret = mkdir(plimitsA, 0777); + if (ret != LOS_OK) { + printf("mkdir failed.\n"); + return LOS_NOK; + } + + /* 设置plimitsA组允许挂载进程个数 */ + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%d", 3); + fd = open(plimitsAPids, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + close(fd); + + /* 挂载进程至plimitsA组 */ + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%d", mainpid); + fd = open(plimitsAProcs, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + close(fd); + + /* 设置plimitsA组内分配内存限额 */ + memset(writeBuf, 0, sizeof(writeBuf)); + //limit memory + sprintf(writeBuf, "%d", (1024*1024*3)); + fd = open(plimitsAMemoryLimit, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + close(fd); + + /* 查看plimitsA组内允许使用的最大内存 */ + memset(readBuf, 0, sizeof(readBuf)); + fd = open(plimitsAMemoryLimit, O_RDONLY); + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(readBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + close(fd); + printf("/proc/plimits/plimitsA组允许使用的最大内存:%s\n", readBuf); + + /* 查看plimitsA组内挂载的进程 */ + memset(readBuf, 0, sizeof(readBuf)); + fd = open(plimitsAProcs, O_RDONLY); + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(readBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + close(fd); + printf("/proc/plimits/plimitsA组内挂载的进程:%s\n", readBuf); + + /* 查看plimitsA组内存的使用情况 */ + mem = (char*)malloc(1024*1024); + memset(mem, 0, 1024); + memset(readBuf, 0, sizeof(readBuf)); + fd = open(plimitsAMemoryUsage, O_RDONLY); + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(readBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + close(fd); + printf("/proc/plimits/plimitsA组已使用内存:%s\n", readBuf); + + /* 删除plimitsA组内memory限制器 */ + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%s", "memory"); + fd = open(plimitsADelete, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + close(fd); + + /* 增加plimitsA组内memory限制器 */ + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%s", "memory"); + fd = open(plimitsAAdd, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + close(fd); + + /* 删除plimitsA组,首先删除memory、pids、sched限制器 */ + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%s", "memory"); + fd = open(plimitsADelete, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%s", "pids"); + fd = open(plimitsADelete, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + + memset(writeBuf, 0, sizeof(writeBuf)); + sprintf(writeBuf, "%s", "sched"); + fd = open(plimitsADelete, O_WRONLY); + len = write(fd, writeBuf, strlen(writeBuf)); + close(fd); + ret = rmdir(plimitsA); + if (ret != LOS_OK) { + printf("rmdir failed.\n"); + return LOS_NOK; + } + + return 0; +} +``` + + +### 结果验证 + +编译运行得到的结果为: + + +``` +/proc/plimits组内进程: +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 + +/proc/plimits组内已使用内存:28016640 + +/proc/plimits/plimitsA组允许使用的最大内存:3145728 + +/proc/plimits/plimitsA组内挂载的进程: +15 + +/proc/plimits/plimitsA组已使用内存:4096 +``` diff --git a/zh-cn/device-dev/reference/hdi-apis/_alloc_info.md b/zh-cn/device-dev/reference/hdi-apis/_alloc_info.md index ccbcd8849e6a1dd3f440561b03a50953475f2248..b75e855aa644a53d4a51f52124346e34c4368d9c 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_alloc_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_alloc_info.md @@ -3,7 +3,7 @@ ## **概述** -定义关于要分配的内存的信息。 +定义待分配的内存的信息。 **相关模块:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_adapter.md b/zh-cn/device-dev/reference/hdi-apis/_audio_adapter.md index be115d34419463c495a8b9e4e4b3f78f44ccbcaf..21b6213df6b8046579946e9992314dadd360fa22 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_adapter.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_adapter.md @@ -5,7 +5,7 @@ AudioAdapter音频适配器接口。 -提供音频适配器(声卡)对外支持的驱动能力,包括初始化端口、创建render、创建capture、获取端口能力集等。 +提供音频适配器(声卡)对外支持的驱动能力,包括初始化端口、创建Render、创建Capture、获取端口能力集等。 **Since:** @@ -34,15 +34,15 @@ AudioAdapter音频适配器接口。 | 名称 | 描述 | | -------- | -------- | | ([InitAllPorts](#initallports))(struct AudioAdapter \*adapter) | 初始化一个音频适配器所有的端口驱动 | -| ([CreateRender](#createrender) )(struct AudioAdapter \*adapter, const struct AudioDeviceDescriptor \*desc, const struct AudioSampleAttributes \*attrs, struct AudioRender \*\*render) | 创建一个音频播放(render)接口的对象 | -| ([DestroyRender](#destroyrender) )(struct AudioAdapter \*adapter, struct AudioRender \*render) | 销毁一个音频播放(render)接口的对象 | -| ([CreateCapture](#createcapture))(struct AudioAdapter \*adapter, const struct AudioDeviceDescriptor \*desc, const struct AudioSampleAttributes \*attrs, struct AudioCapture \*\*capture) | 创建一个音频录音(capture)接口的对象 | -| ([DestroyCapture](#destroycapture))(struct AudioAdapter \*adapter, struct AudioCapture \*capture) | 销毁一个音频录音(capture)接口的对象 | +| ([CreateRender](#createrender) )(struct AudioAdapter \*adapter, const struct AudioDeviceDescriptor \*desc, const struct AudioSampleAttributes \*attrs, struct AudioRender \*\*render) | 创建一个音频播放(Render)接口的对象 | +| ([DestroyRender](#destroyrender) )(struct AudioAdapter \*adapter, struct AudioRender \*render) | 销毁一个音频播放(Render)接口的对象 | +| ([CreateCapture](#createcapture))(struct AudioAdapter \*adapter, const struct AudioDeviceDescriptor \*desc, const struct AudioSampleAttributes \*attrs, struct AudioCapture \*\*capture) | 创建一个音频录音(Capture)接口的对象 | +| ([DestroyCapture](#destroycapture))(struct AudioAdapter \*adapter, struct AudioCapture \*capture) | 销毁一个音频录音(Capture)接口的对象 | | ([GetPortCapability](#getportcapability) )(struct AudioAdapter \*adapter, struct AudioPort \*port, struct AudioPortCapability \*capability) | 获取一个音频适配器的端口驱动的能力集 | | ([SetPassthroughMode](#setpassthroughmode) )(struct AudioAdapter \*adapter, struct AudioPort \*port, enum AudioPortPassthroughMode mode) | 设置音频端口驱动的数据透传模式 | | ([GetPassthroughMode](#getpassthroughmode))(struct AudioAdapter \*adapter, struct AudioPort \*port, enum AudioPortPassthroughMode \*mode) | 获取音频端口驱动的数据透传模式 | | ([UpdateAudioRoute](#updateaudioroute))(struct AudioAdapter \*adapter, const struct AudioRoute \*route, int32_t \*routeHandle) | 更新一个或多个发送端和接受端之间的路由 | -| ([ReleaseAudioRoute](#releaseaudioroute))(struct AudioAdapter \*adapter, int32_t routeHandle) | 释放一个音频路由. | +| ([ReleaseAudioRoute](#releaseaudioroute))(struct AudioAdapter \*adapter, int32_t routeHandle) | 释放一个音频路由 | ## **类成员变量说明** @@ -57,7 +57,7 @@ int32_t(* AudioAdapter::CreateCapture) (struct AudioAdapter *adapter, const stru **描述:** -创建一个音频录音(capture)接口的对象 +创建一个音频录音(Capture)接口的对象。 **参数:** @@ -70,7 +70,7 @@ int32_t(* AudioAdapter::CreateCapture) (struct AudioAdapter *adapter, const stru **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -88,7 +88,7 @@ int32_t(* AudioAdapter::CreateRender) (struct AudioAdapter *adapter, const struc **描述:** -创建一个音频播放(render)接口的对象 +创建一个音频播放(Render)接口的对象。 **参数:** @@ -101,7 +101,7 @@ int32_t(* AudioAdapter::CreateRender) (struct AudioAdapter *adapter, const struc **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -119,7 +119,7 @@ int32_t(* AudioAdapter::DestroyCapture) (struct AudioAdapter *adapter, struct Au **描述:** -销毁一个音频录音(capture)接口的对象 +销毁一个音频录音(Capture)接口的对象。 **参数:** @@ -130,11 +130,11 @@ int32_t(* AudioAdapter::DestroyCapture) (struct AudioAdapter *adapter, struct Au **注意:** -在音频录音过程中,不能销毁该接口对象 +在音频录音过程中,不能销毁该接口对象。 **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -150,7 +150,7 @@ int32_t(* AudioAdapter::DestroyRender) (struct AudioAdapter *adapter, struct Aud **描述:** -销毁一个音频播放(render)接口的对象 +销毁一个音频播放(Render)接口的对象。 **参数:** @@ -165,7 +165,7 @@ int32_t(* AudioAdapter::DestroyRender) (struct AudioAdapter *adapter, struct Aud **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -181,7 +181,7 @@ int(* AudioAdapter::GetPassthroughMode) (struct AudioAdapter *adapter, struct Au **描述:** -获取音频端口驱动的数据透传模式 +获取音频端口驱动的数据透传模式。 **参数:** @@ -193,7 +193,7 @@ int(* AudioAdapter::GetPassthroughMode) (struct AudioAdapter *adapter, struct Au **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -209,7 +209,7 @@ int(* AudioAdapter::GetPortCapability) (struct AudioAdapter *adapter, struct Aud **描述:** -获取一个音频适配器的端口驱动的能力集 +获取一个音频适配器的端口驱动的能力集。 **参数:** @@ -221,7 +221,7 @@ int(* AudioAdapter::GetPortCapability) (struct AudioAdapter *adapter, struct Aud **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### InitAllPorts @@ -249,7 +249,7 @@ int(* AudioAdapter::InitAllPorts) (struct AudioAdapter *adapter) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### ReleaseAudioRoute @@ -261,18 +261,18 @@ int32_t(* AudioAdapter::ReleaseAudioRoute) (struct AudioAdapter *adapter, int32_ **描述:** -释放一个音频路由. +释放一个音频路由。 **参数:** | 名称 | 描述 | | -------- | -------- | | adapter | 待操作的音频适配器对象 | -| routeHandle | 待释放的路由句柄. | +| routeHandle | 待释放的路由句柄 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetPassthroughMode @@ -284,7 +284,7 @@ int(* AudioAdapter::SetPassthroughMode) (struct AudioAdapter *adapter, struct Au **描述:** -设置音频端口驱动的数据透传模式 +设置音频端口驱动的数据透传模式。 **参数:** @@ -296,7 +296,7 @@ int(* AudioAdapter::SetPassthroughMode) (struct AudioAdapter *adapter, struct Au **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -312,7 +312,7 @@ int32_t(* AudioAdapter::UpdateAudioRoute) (struct AudioAdapter *adapter, const s **描述:** -更新一个或多个发送端和接受端之间的路由 +更新一个或多个发送端和接受端之间的路由。 **参数:** @@ -324,4 +324,4 @@ int32_t(* AudioAdapter::UpdateAudioRoute) (struct AudioAdapter *adapter, const s **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md b/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md index 91b7118108cc00bdce8ecfc2931789e5bbb40ba3..32fb2917b206ae9297f47d920e61a9c1cac27323 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md @@ -5,7 +5,7 @@ AudioAttribute音频属性接口。 -提供音频播放(render)或录音(capture)需要的公共属性驱动能力,包括获取帧(frame)信息、设置采样属性等。 +提供音频播放(Render)或录音(Capture)需要的公共属性驱动能力,包括获取帧(frame)信息、设置采样属性等。 **Since:** @@ -34,8 +34,8 @@ AudioAttribute音频属性接口。 | ([GetCurrentChannelId](#getcurrentchannelid))(AudioHandle handle, uint32_t \*channelId) | 获取音频的数据通道ID | | ([SetExtraParams](#setextraparams))(AudioHandle handle, const char \*keyValueList) | 设置音频拓展参数 | | ([GetExtraParams](#getextraparams))(AudioHandle handle, char \*keyValueList) | 获取音频拓展参数 | -| ([ReqMmapBuffer](#reqmmapbuffer))(AudioHandle handle, int32_t reqSize, struct AudioMmapBufferDescripter \*desc) | 请求mmap缓冲区 | -| ([GetMmapPosition](#getmmapposition))(AudioHandle handle, uint64_t \*frames, struct AudioTimeStamp \*time) | 获取当前mmap的读/写位置 | +| ([ReqMmapBuffer](#reqmmapbuffer))(AudioHandle handle, int32_t reqSize, struct AudioMmapBufferDescripter \*desc) | 请求Mmap缓冲区 | +| ([GetMmapPosition](#getmmapposition))(AudioHandle handle, uint64_t \*frames, struct AudioTimeStamp \*time) | 获取当前Mmap的读/写位置 | | ([AddAudioEffect](#addaudioeffect))(AudioHandle handle, uint64_t effectid) | 添加音频效果算法实例 | | ([RemoveAudioEffect](#removeaudioeffect))(AudioHandle handle, uint64_t effectid) | 移除音频效果算法实例 | | ([GetFrameBufferSize](#getframebuffersize))(AudioHandle handle, uint64_t \*bufferSize) | 获取播放或录音的缓冲区大小 | @@ -53,7 +53,7 @@ int32_t (*AudioAttribute::AddAudioEffect)(AudioHandle handle, uint64_t effectid) **描述:** -添加音频效果算法实例 +添加音频效果算法实例。 **参数:** @@ -64,7 +64,7 @@ int32_t (*AudioAttribute::AddAudioEffect)(AudioHandle handle, uint64_t effectid) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetCurrentChannelId @@ -76,18 +76,18 @@ int32_t(* AudioAttribute::GetCurrentChannelId) (AudioHandle handle, uint32_t *ch **描述:** -获取音频的数据通道ID +获取音频的数据通道ID。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| channelId | 获取的通道ID保存到channelId中 | +| handle | 输入参数,待操作的音频句柄。 | +| channelId | 输出参数,获取的通道ID保存到channelId中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetExtraParams @@ -99,18 +99,18 @@ int32_t(* AudioAttribute::GetExtraParams) (AudioHandle handle, char *keyValueLis **描述:** -获取音频拓展参数 +获取音频拓展参数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | +| handle | 输入参数,待操作的音频句柄。 | +| keyValueList | 输出参数,拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetFrameBufferSize @@ -122,7 +122,7 @@ int32_t (*AudioAttribute::GetFrameBufferSize)(AudioHandle handle, uint64_t *buff **描述:** -获取播放或录音的缓冲区大小 +获取播放或录音的缓冲区大小。 **参数:** @@ -145,18 +145,18 @@ int32_t(* AudioAttribute::GetFrameCount) (AudioHandle handle, uint64_t *count) **描述:** -获取音频buffer中的音频帧数 +获取音频buffer中的音频帧数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| count | 一个音频buffer中包含的音频帧数,获取后保存到count中 | +| handle | 输入参数,待操作的音频句柄。 | +| count | 输出参数,一个音频buffer中包含的音频帧数,获取后保存到count中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetFrameSize @@ -168,20 +168,18 @@ int32_t(* AudioAttribute::GetFrameSize) (AudioHandle handle, uint64_t *size) **描述:** -获取音频帧(frame)的大小 - -获取一帧音频数据的长度(字节数) +获取音频帧(frame)的大小,即一帧音频数据的长度(字节数)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| size | 获取的音频帧大小(字节数)保存到size中 | +| handle | 输入参数,待操作的音频句柄。 | +| size | 输出参数,获取的音频帧大小(字节数)保存到size中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetMmapPosition @@ -193,19 +191,19 @@ int32_t(* AudioAttribute::GetMmapPosition) (AudioHandle handle, uint64_t *frames **描述:** -获取当前mmap的读/写位置 +获取当前Mmap的读/写位置。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| frames | 获取的音频帧计数保存到frames中 | -| time | 获取的关联时间戳保存到time中 | +| handle | 输入参数,待操作的音频句柄。 | +| frames | 输出参数,获取的音频帧计数保存到frames中。 | +| time | 输出参数,获取的关联时间戳保存到time中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetSampleAttributes @@ -217,14 +215,14 @@ int32_t(* AudioAttribute::GetSampleAttributes) (AudioHandle handle, struct Audio **描述:** -获取音频采样的属性参数 +获取音频采样的属性参数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| attrs | 获取的音频采样属性(例如采样频率、采样精度、通道)保存到attrs中 | +| handle | 输入参数,待操作的音频句柄。 | +| attrs | 输出参数,获取的音频采样属性(例如采样频率、采样精度、通道)保存到attrs中。 | **返回:** @@ -244,7 +242,7 @@ int32_t (*AudioAttribute::RemoveAudioEffect)(AudioHandle handle, uint64_t effect **描述:** -移除音频效果算法实例 +移除音频效果算法实例。 **参数:** @@ -267,19 +265,19 @@ int32_t(* AudioAttribute::ReqMmapBuffer) (AudioHandle handle, int32_t reqSize, s **描述:** -请求mmap缓冲区 +请求Mmap缓冲区。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| reqSize | 请求缓冲区的大小 | -| desc | 缓冲区描述符 | +| handle | 输入参数,待操作的音频句柄。 | +| reqSize | 输入参数,请求缓冲区的大小。 | +| desc | 输出参数,缓冲区描述符。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetExtraParams @@ -291,18 +289,18 @@ int32_t(* AudioAttribute::SetExtraParams) (AudioHandle handle, const char *keyVa **描述:** -设置音频拓展参数 +设置音频拓展参数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | +| handle | 输入参数,待操作的音频句柄。 | +| keyValueList | 输入参数,拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetSampleAttributes @@ -314,18 +312,18 @@ int32_t(* AudioAttribute::SetSampleAttributes) (AudioHandle handle, const struct **描述:** -设置音频采样的属性参数 +设置音频采样的属性参数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| attrs | 待设置的音频采样属性,例如采样频率、采样精度、通道 | +| handle | 输入参数,待操作的音频句柄。 | +| attrs | 输入参数,待设置的音频采样属性,例如采样频率、采样精度、通道。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_capture.md b/zh-cn/device-dev/reference/hdi-apis/_audio_capture.md index 9f316b158812e5d3de68fbd18ccbbf6cfd659a57..c3cecd48016cf8819856ae7cf1eccf85fe778c86 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_capture.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_capture.md @@ -21,7 +21,7 @@ AudioCapture录音接口。 | attr | 音频属性能力接口,详情参考[AudioAttribute](_audio_attribute.md)。 | | scene | 音频场景能力接口,详情参考[AudioScene](_audio_scene.md)。 | | volume | 音频音量能力接口,详情参考[AudioVolume](_audio_volume.md)。 | -| ([CaptureFrame](#captureframe))(struct AudioCapture \*capture, void \*frame, uint64_t requestBytes, uint64_t \*replyBytes) | 从音频驱动中录制(capture)一帧输入数据(录音,音频上行数据)。 | +| ([CaptureFrame](#captureframe))(struct AudioCapture \*capture, void \*frame, uint64_t requestBytes, uint64_t \*replyBytes) | 从音频驱动中录制(Capture)一帧输入数据(录音,音频上行数据)。 | | ([GetCapturePosition](#getcaptureposition))(struct AudioCapture \*capture, uint64_t \*frames, struct AudioTimeStamp \*time) | 获取音频输入帧数的上一次计数。 | @@ -37,20 +37,20 @@ int32_t(* AudioCapture::CaptureFrame) (struct AudioCapture *capture, void *frame **描述:** -从音频驱动中录制(capture)一帧输入数据(录音,音频上行数据) +从音频驱动中录制(Capture)一帧输入数据(录音,音频上行数据)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| capture | 待操作的音频录音接口对象 | -| frame | 待存放输入数据的音频frame | -| requestBytes | 待存放输入数据的音频frame大小(字节数) | -| replyBytes | 实际读取到的音频数据长度(字节数),获取后保存到replyBytes中 | +| capture | 输入参数,待操作的音频录音接口对象。 | +| frame | 输入参数,待存放输入数据的音频frame。 | +| requestBytes | 输入参数,待存放输入数据的音频frame大小(字节数)。 | +| replyBytes | 输出参数,实际读取到的音频数据长度(字节数),获取后保存到replyBytes中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetCapturePosition @@ -62,19 +62,19 @@ int32_t(* AudioCapture::GetCapturePosition) (struct AudioCapture *capture, uint6 **描述:** -获取音频输入帧数的上一次计数 +获取音频输入帧数的上一次计数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| capture | 待操作的音频录音接口对象 | -| frames | 获取的音频帧计数保存到frames中 | -| time | 获取的关联时间戳保存到time中 | +| capture | 输入参数,待操作的音频录音接口对象。| +| frames | 输出参数,获取的音频帧计数保存到frames中。 | +| time | 输出参数,获取的关联时间戳保存到time中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_control.md b/zh-cn/device-dev/reference/hdi-apis/_audio_control.md index 0a7c29043458659885ef3be77f83309b93364b76..368c9f34b2028cbd0a4b99d7abf6bb0ebe502fdc 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_control.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_control.md @@ -3,9 +3,9 @@ ## **概述** -AudioControl音频控制接口 +AudioControl音频控制接口。 -提供音频播放(render)或录音(capture)需要的公共控制驱动能力,包括Start、Stop、Pause、Resume、Flush等。 +提供音频播放(Render)或录音(Capture)需要的公共控制驱动能力,包括Start、Stop、Pause、Resume、Flush等。 **Since:** @@ -27,13 +27,13 @@ AudioControl音频控制接口 | 名称 | 描述 | | -------- | -------- | -| ([Start](#start))(AudioHandle handle) | 启动一个音频播放(render)或录音(capture)处理 | -| ([Stop](#stop))(AudioHandle handle) | 停止一个音频播放(render)或录音(capture)处理 | -| ([Pause](#pause))(AudioHandle handle) | 暂停一个音频播放(render)或录音(capture)处理 | -| ([Resume](#resume))(AudioHandle handle) | 恢复一个音频播放(render)或录音(capture)处理 | -| ([Flush](#flush))(AudioHandle handle) | 刷新音频缓冲区buffer中的数据 | -| ([TurnStandbyMode](#turnstandbymode))(AudioHandle handle) | 设置或去设置设备的待机模式 | -| ([AudioDevDump](#audiodevdump))(AudioHandle handle, int32_t range, int32_t fd) | Dump音频设备信息 | +| ([Start](#start))(AudioHandle handle) | 启动一个音频播放(Render)或录音(Capture)处理。 | +| ([Stop](#stop))(AudioHandle handle) | 停止一个音频播放(Render)或录音(Capture)处理。 | +| ([Pause](#pause))(AudioHandle handle) | 暂停一个音频播放(Render)或录音(Capture)处理。 | +| ([Resume](#resume))(AudioHandle handle) | 恢复一个音频播放(Render)或录音(Capture)处理。 | +| ([Flush](#flush))(AudioHandle handle) | 刷新音频缓冲区buffer中的数据。 | +| ([TurnStandbyMode](#turnstandbymode))(AudioHandle handle) | 设置或去设置设备的待机模式。 | +| ([AudioDevDump](#audiodevdump))(AudioHandle handle, int32_t range, int32_t fd) | Dump音频设备信息。 | ## **类成员变量说明** @@ -48,7 +48,7 @@ int32_t(* AudioControl::AudioDevDump) (AudioHandle handle, int32_t range, int32_ **描述:** -Dump音频设备信息 +Dump音频设备信息。 **参数:** @@ -60,7 +60,7 @@ Dump音频设备信息 **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### Flush @@ -72,7 +72,7 @@ int32_t(* AudioControl::Flush) (AudioHandle handle) **描述:** -刷新音频缓冲区buffer中的数据 +刷新音频缓冲区buffer中的数据。 **参数:** @@ -82,7 +82,7 @@ int32_t(* AudioControl::Flush) (AudioHandle handle) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### Pause @@ -94,7 +94,7 @@ int32_t(* AudioControl::Pause) (AudioHandle handle) **描述:** -暂停一个音频播放(render)或录音(capture)处理 +暂停一个音频播放(Render)或录音(Capture)处理。 **参数:** @@ -104,7 +104,7 @@ int32_t(* AudioControl::Pause) (AudioHandle handle) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -120,7 +120,7 @@ int32_t(* AudioControl::Resume) (AudioHandle handle) **描述:** -恢复一个音频播放(render)或录音(capture)处理 +恢复一个音频播放(Render)或录音(Capture)处理。 **参数:** @@ -130,7 +130,7 @@ int32_t(* AudioControl::Resume) (AudioHandle handle) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -146,7 +146,7 @@ int32_t(* AudioControl::Start) (AudioHandle handle) **描述:** -启动一个音频播放(render)或录音(capture)处理 +启动一个音频播放(Render)或录音(Capture)处理。 **参数:** @@ -156,7 +156,7 @@ int32_t(* AudioControl::Start) (AudioHandle handle) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -172,7 +172,7 @@ int32_t(* AudioControl::Stop) (AudioHandle handle) **描述:** -停止一个音频播放(render)或录音(capture)处理 +停止一个音频播放(Render)或录音(Capture)处理。 **参数:** @@ -182,7 +182,7 @@ int32_t(* AudioControl::Stop) (AudioHandle handle) **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -198,7 +198,7 @@ int32_t(* AudioControl::TurnStandbyMode) (AudioHandle handle) **描述:** -设置或去设置设备的待机模式 +设置或去设置设备的待机模式。 **参数:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_manager.md b/zh-cn/device-dev/reference/hdi-apis/_audio_manager.md index d0ad0ecea2c79788ef86f7b9bcd5d130aeb3485a..c809c03c0b8835dcea26e5d18c48cf05d59f3211 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_manager.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_manager.md @@ -49,19 +49,19 @@ int(* AudioManager::GetAllAdapters) (struct AudioAdapterManager *manager, struct **描述:** -获取音频驱动中支持的所有适配器的列表 +获取音频驱动中支持的所有适配器的列表。 **参数:** | 名称 | 描述 | | -------- | -------- | -| manager | 待操作的音频管理接口对象 | -| descs | 获取到的音频适配器列表保存到descs中 | -| size | 获取到的音频适配器列表的长度保存到size中 | +| manager | 输入参数,待操作的音频管理接口对象。 | +| descs | 输出参数,获取到的音频适配器列表保存到descs中。 | +| size | 输出参数,获取到的音频适配器列表的长度保存到size中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -77,21 +77,21 @@ int(* AudioManager::LoadAdapter) (struct AudioAdapterManager *manager, const str **描述:** -加载一个音频适配器(声卡)的驱动 +加载一个音频适配器(声卡)的驱动。 -加载一个具体的音频驱动,例如usb驱动,在具体实现中可能加载的是一个动态链接库(\*.so) +加载一个具体的音频驱动,例如USB驱动,在具体实现中可能加载的是一个动态链接库(\*.so)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| manager | 待操作的音频管理接口对象 | -| desc | 待加载的音频适配器描述符 | -| adapter | 获取的音频适配器接口的对象实例保存到adapter中 | +| manager | 输入参数,待操作的音频管理接口对象。 | +| desc | 输入参数,待加载的音频适配器描述符。 | +| adapter | 输出参数,获取的音频适配器接口的对象实例保存到adapter中。| **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -109,17 +109,17 @@ bool(* AudioManager::ReleaseAudioManagerObject) (struct AudioManager *object) **描述:** -释放音频管理接口对象 +释放音频管理接口对象。 **参数:** | 名称 | 描述 | | -------- | -------- | -| 待操作的音频管理接口对象 | | +| object | 输入参数,待操作的音频管理接口对象。 | **返回:** -成功返回true,失败返回false +成功返回true,失败返回false。 ### UnloadAdapter @@ -131,14 +131,14 @@ void(* AudioManager::UnloadAdapter) (struct AudioAdapterManager *manager, struct **描述:** -卸载音频适配器(声卡)的驱动 +卸载音频适配器(声卡)的驱动。 **参数:** | 名称 | 描述 | | -------- | -------- | -| manager | 待操作的音频管理接口对象 | -| adapter | 待卸载的音频适配器接口的对象 | +| manager | 输入参数,待操作的音频管理接口对象。 | +| adapter | 输入参数,待卸载的音频适配器接口的对象。 | **参见:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_mmap_buffer_descripter.md b/zh-cn/device-dev/reference/hdi-apis/_audio_mmap_buffer_descripter.md index ae1a56a61e43026fdf892b4c956a884c4d6cce2b..93470c6b005a438663e7efd1b8e6ec204701af20 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_mmap_buffer_descripter.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_mmap_buffer_descripter.md @@ -17,8 +17,8 @@ Mmap缓冲区描述符。 | 名称 | 描述 | | -------- | -------- | -| [memoryAddress](_audio.md#memoryaddress) | 指向mmap缓冲区的指针 | -| [memoryFd](_audio.md#memoryfd) | mmap缓冲区的文件描述符 | +| [memoryAddress](_audio.md#memoryaddress) | 指向Mmap缓冲区的指针 | +| [memoryFd](_audio.md#memoryfd) | Mmap缓冲区的文件描述符 | | [totalBufferFrames](_audio.md#totalbufferframes) | 缓冲区总大小,单位:帧 | | [transferFrameSize](_audio.md#transferframesize) | 传输大小,单位:帧 | -| [isShareable](_audio.md#isshareable) | mmap缓冲区是否可以在进程间共享 | +| [isShareable](_audio.md#isshareable) | Mmap缓冲区是否可以在进程间共享 | diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_render.md b/zh-cn/device-dev/reference/hdi-apis/_audio_render.md index c4a172ab2af2c546cb3a33363d254dcebd9b5de6..c7aed448a1393871e2325b41f47be8edeae7bfee 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_render.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_render.md @@ -5,7 +5,7 @@ AudioRender音频播放接口。 -提供音频播放支持的驱动能力,包括音频控制、音频属性、音频场景、音频音量、获取硬件延迟时间、播放音频帧数据(render frame)等。 +提供音频播放支持的驱动能力,包括音频控制、音频属性、音频场景、音频音量、获取硬件延迟时间、播放音频帧数据(Render frame)等。 **Since:** @@ -42,7 +42,7 @@ AudioRender音频播放接口。 | scene | 音频场景能力接口,详情参考[AudioScene](_audio_scene.md)。 | | volume | 音频音量能力接口,详情参考[AudioVolume](_audio_volume.md)。 | | ([GetLatency](#getlatency))(struct AudioRender \*render, uint32_t \*ms) | 获取音频硬件驱动估计的延迟时间。 | -| ([RenderFrame](#renderframe))(struct AudioRender \*render, const void \*frame, uint64_t requestBytes, uint64_t \*replyBytes) | 往音频驱动中播放(render)一帧输出数据(放音,音频下行数据)。 | +| ([RenderFrame](#renderframe))(struct AudioRender \*render, const void \*frame, uint64_t requestBytes, uint64_t \*replyBytes) | 往音频驱动中播放(Render)一帧输出数据(放音,音频下行数据)。 | | ([GetRenderPosition](#getrenderposition))(struct AudioRender \*render, uint64_t \*frames, struct AudioTimeStamp \*time) | 获取音频输出帧数的上一次计数。 | | ([SetRenderSpeed](#setrenderspeed))(struct AudioRender \*render, float speed) | 设置一个音频的播放速度。 | | ([GetRenderSpeed](#getrenderspeed))(struct AudioRender \*render, float \*speed) | 获取一个音频当前的播放速度。 | @@ -64,18 +64,18 @@ int32_t(* AudioRender::DrainBuffer) (struct AudioRender *render, enum AudioDrain **描述:** -排空缓冲区中的数据 +排空缓冲区中的数据。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| type | DrainBuffer的操作类型,详情请参考[AudioDrainNotifyType](_audio.md#audiodrainnotifytype)。 | +| render | 输入参数,待操作的音频播放接口对象。 | +| type | 输入参数,DrainBuffer的操作类型,详情请参考[AudioDrainNotifyType](_audio.md#audiodrainnotifytype)。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -91,18 +91,18 @@ int32_t(* AudioRender::GetChannelMode) (struct AudioRender *render, enum AudioCh **描述:** -获取音频播放当前的通道模式 +获取音频播放当前的通道模式。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| mode | 获取的通道模式保存到mode中 | +| render | 输入参数,待操作的音频播放接口对象。| +| mode | 输出参数,获取的通道模式保存到mode中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -118,18 +118,18 @@ int32_t(* AudioRender::GetLatency) (struct AudioRender *render, uint32_t *ms) **描述:** -获取音频硬件驱动估计的延迟时间 +获取音频硬件驱动估计的延迟时间。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| ms | 获取的延迟时间(单位:毫秒)保存到ms中 | +| render | 输入参数,待操作的音频播放接口对象。 | +| ms | 输出参数,获取的延迟时间(单位:毫秒)保存到ms中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetRenderPosition @@ -141,19 +141,19 @@ int32_t(* AudioRender::GetRenderPosition) (struct AudioRender *render, uint64_t **描述:** -获取音频输出帧数的上一次计数 +获取音频输出帧数的上一次计数。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| frames | 获取的音频帧计数保存到frames中 | -| time | 获取的关联时间戳保存到time中 | +| render | 输入参数,待操作的音频播放接口对象。 | +| frames | 输出参数,获取的音频帧计数保存到frames中。 | +| time | 输出参数,获取的关联时间戳保存到time中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -169,18 +169,18 @@ int32_t(* AudioRender::GetRenderSpeed) (struct AudioRender *render, float *speed **描述:** -获取一个音频当前的播放速度 +获取一个音频当前的播放速度。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| speed | 获取的播放速度保存到speed中 | +| render | 输入参数,待操作的音频播放接口对象。 | +| speed | 输出参数,获取的播放速度保存到speed中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -196,19 +196,19 @@ int32_t(* AudioRender::RegCallback) (struct AudioRender *render, RenderCallback **描述:** -注册音频回调函数,用于放音过程中缓冲区数据写、DrainBuffer完成通知 +注册音频回调函数,用于放音过程中缓冲区数据写、DrainBuffer完成通知。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| callback | 注册的回调函数 | -| cookie | 回调函数的入参 | +| render | 输入参数,待操作的音频播放接口对象。 | +| callback | 输入参数,注册的回调函数。 | +| cookie | 输入参数,回调函数的入参。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -224,20 +224,20 @@ int32_t(* AudioRender::RenderFrame) (struct AudioRender *render, const void *fra **描述:** -往音频驱动中播放(render)一帧输出数据(放音,音频下行数据) +向音频驱动中播放(Render)一帧输出数据(放音,音频下行数据)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| frame | 待写入的输出数据的音频frame | -| requestBytes | 待写入的输出数据的音频frame大小(字节数) | -| replyBytes | 实际写入的音频数据长度(字节数),获取后保存到replyBytes中 | +| render | 输入参数,待操作的音频播放接口对象。 | +| frame | 输入参数,待写入的输出数据的音频frame。 | +| requestBytes | 输入参数,待写入的输出数据的音频frame大小(字节数)。 | +| replyBytes | 输出参数,实际写入的音频数据长度(字节数),获取后保存到replyBytes中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetChannelMode @@ -249,18 +249,18 @@ int32_t(* AudioRender::SetChannelMode) (struct AudioRender *render, enum AudioCh **描述:** -设置音频播放的通道模式 +设置音频播放的通道模式。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| speed | 待设置的通道模式 | +| render | 输入参数,待操作的音频播放接口对象。 | +| speed | 输入参数,待设置的通道模式。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -276,18 +276,18 @@ int32_t(* AudioRender::SetRenderSpeed) (struct AudioRender *render, float speed) **描述:** -设置一个音频的播放速度 +设置一个音频的播放速度。 **参数:** | 名称 | 描述 | | -------- | -------- | -| render | 待操作的音频播放接口对象 | -| speed | 待设置的播放速度 | +| render | 输入参数,待操作的音频播放接口对象。 | +| speed | 输入参数,待设置的播放速度。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_scene.md b/zh-cn/device-dev/reference/hdi-apis/_audio_scene.md index 27bf2daee3c3eaf3da86ab30c5d6a24dca4feeb2..f2bf7f3c7639d81dbe4f3ef17c511659dbcf02d3 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_scene.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_scene.md @@ -43,19 +43,19 @@ int32_t(* AudioScene::CheckSceneCapability) (AudioHandle handle, const struct Au **描述:** -是否支持某个音频场景的配置 +是否支持某个音频场景的配置。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| scene | 待获取的音频场景描述符 | -| supported | 是否支持的状态保存到supported中,true表示支持,false表示不支持 | +| handle | 输入参数,待操作的音频句柄。 | +| scene | 输入参数,待获取的音频场景描述符。 | +| supported | 输出参数,是否支持的状态保存到supported中,true表示支持,false表示不支持。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -71,26 +71,26 @@ int32_t(* AudioScene::SelectScene) (AudioHandle handle, const struct AudioSceneD **描述:** -选择音频场景 +选择音频场景。 -- 1. 选择一个非常具体的音频场景(应用场景和输出设备的组合),例如同样是使用手机中的喇叭作为输出设备 +- 选择一个非常具体的音频场景(应用场景和输出设备的组合),例如同样是使用手机中的喇叭作为输出设备: - 在媒体播放场景scene为media_speaker - 在语音通话免提场景scene为voice_speaker -- 2. 只是选择一个音频场景,例如使用场景为媒体播放(media)、电影播放(movie)、游戏播放(game) +- 只是选择一个音频场景,例如使用场景为媒体播放(media)、电影播放(movie)、游戏播放(game)。 -- 3. 只是选择一个音频输出设备,例如输出设备为听筒(receiver)、喇叭(speaker)、有线耳机(headset) +- 只是选择一个音频输出设备,例如输出设备为听筒(receiver)、喇叭(speaker)、有线耳机(headset)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| scene | 待设置的音频场景描述符 | +| handle | 输入参数,待操作的音频句柄。 | +| scene | 输入参数,待设置的音频场景描述符。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_volume.md b/zh-cn/device-dev/reference/hdi-apis/_audio_volume.md index a4872b457d81268fcf4bcf13e7c6f056f965cbbb..677f5f1999aee3d67a1d6ed0df577ca08eafde16 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_volume.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_volume.md @@ -5,7 +5,7 @@ AudioVolume音频音量接口。 -提供音频播放(render)或录音(capture)需要的公共音量驱动能力,包括静音操作、设置音量、设置增益等。 +提供音频播放(Render)或录音(Capture)需要的公共音量驱动能力,包括静音操作、设置音量、设置增益等。 **Since:** @@ -48,18 +48,18 @@ int32_t(* AudioVolume::GetGain) (AudioHandle handle, float *gain) **描述:** -获取音频流的增益 +获取音频流的增益。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| gain | 保存当前获取到的增益到gain中 | +| handle | 输入参数,待操作的音频句柄。 | +| gain | 输出参数,保存当前获取到的增益到gain中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -77,7 +77,7 @@ int32_t(* AudioVolume::GetGainThreshold) (AudioHandle handle, float *min, float **描述:** -获取音频流增益的阈值 +获取音频流增益的阈值。 在具体的功能实现中,可以根据芯片平台的实际情况来进行处理: @@ -89,13 +89,13 @@ int32_t(* AudioVolume::GetGainThreshold) (AudioHandle handle, float *min, float | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| min | 获取的音频增益的阈值下限保存到min中 | -| max | 获取的音频增益的阈值上限保存到max中 | +| handle | 输入参数,待操作的音频句柄。 | +| min | 输出参数,获取的音频增益的阈值下限保存到min中。 | +| max | 输出参数,获取的音频增益的阈值上限保存到max中。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -113,18 +113,18 @@ int32_t(* AudioVolume::GetMute) (AudioHandle handle, bool *mute) **描述:** -获取音频的静音状态 +获取音频的静音状态。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| mute | 获取的静音状态保存到mute中,true表示静音操作、false表示取消静音操作 | +| handle | 输入参数,待操作的音频句柄。 | +| mute | 输出参数,获取的静音状态保存到mute中,true表示静音操作,false表示取消静音操作。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -140,18 +140,18 @@ int32_t(* AudioVolume::GetVolume) (AudioHandle handle, float *volume) **描述:** -获取一个音频流的音量 +获取一个音频流的音量。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| volume | 获取的音量保存到volume中,范围0.0~1.0 | +| handle | 输入参数,待操作的音频句柄。 | +| volume | 输出参数,获取的音量保存到volume中,范围0.0~1.0。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -167,18 +167,18 @@ int32_t(* AudioVolume::SetGain) (AudioHandle handle, float gain) **描述:** -设置音频流的增益 +设置音频流的增益。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| gain | gain 待设置的增益 | +| handle | 输入参数,待操作的音频句柄。 | +| gain | 输入参数,待设置的增益。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -196,18 +196,18 @@ int32_t(* AudioVolume::SetMute) (AudioHandle handle, bool mute) **描述:** -设置音频的静音状态 +设置音频的静音状态。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| mute | 待设置的静音状态,true表示静音操作、false表示取消静音操作 | +| handle | 输入参数,待操作的音频句柄。 | +| mute | 输入参数,待设置的静音状态,true表示静音操作,false表示取消静音操作。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -225,15 +225,15 @@ int32_t(* AudioVolume::SetVolume) (AudioHandle handle, float volume) 设置一个音频流的音量。 -音量的取值范围是0.0~1.0,如果音频服务中的音量等级为15级(0 ~ 15), 则音量的映射关系为0.0表示静音,1.0表示最大音量等级(15)。 +音量的取值范围是0.0~1.0,如果音频服务中的音量等级为15级(0 ~ 15),则音量的映射关系为0.0表示静音,1.0表示最大音量等级(15)。 **参数:** | 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| volume | 待设置的音量,范围0.0~1.0 | +| handle | 输入参数,待操作的音频句柄。 | +| volume | 输入参数,待设置的音量,范围0.0~1.0。 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_ext_data_handle.md b/zh-cn/device-dev/reference/hdi-apis/_ext_data_handle.md index 51239a52338c14e4d3a360136e58c80b73a64df7..eb120bcd201dd27759e96c7dd73872c7f004b28e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_ext_data_handle.md +++ b/zh-cn/device-dev/reference/hdi-apis/_ext_data_handle.md @@ -17,6 +17,6 @@ | 名称 | 描述 | | -------- | -------- | -| [fd](_display.md#fd) | 句柄 fd, -1代表不支持。 | +| [fd](_display.md#fd) | 句柄fd,-1代表不支持。 | | [reserveInts](_display.md#reserveints) | reserve数组的个数。 | | [reserve](_display.md#reserve) [0] | reserve数组。 | diff --git a/zh-cn/device-dev/reference/hdi-apis/_i_wlan_interface_8idl.md b/zh-cn/device-dev/reference/hdi-apis/_i_wlan_interface_8idl.md index c29124f5e5f131c61798081b8f95a1d97360ffce..adaa08cb01c1d4e01d58f984623fd0d762a7a56e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_i_wlan_interface_8idl.md +++ b/zh-cn/device-dev/reference/hdi-apis/_i_wlan_interface_8idl.md @@ -3,9 +3,7 @@ ## **概述** -建立/关闭WLAN热点,扫描/关联/去关联WLAN热点,设置国家码,管理网络设备等操作的接口。 - -上层服务调用相关的接口实现:建立/关闭WLAN热点,扫描/关联/去关联WLAN热点,设置国家码,管理网络设备等功能。 +WLAN模块操作接口,上层服务调用相关的接口可实现:建立/关闭WLAN热点,扫描/关联/去关联WLAN热点,设置国家码,管理网络设备等功能。 **Since:** diff --git a/zh-cn/device-dev/reference/hdi-apis/_wlan_types_8idl.md b/zh-cn/device-dev/reference/hdi-apis/_wlan_types_8idl.md index a0919917f8cad341d90e5637c1ed462b457832f9..03cc663f0672292fae1a77a5f912f80050ee946f 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_wlan_types_8idl.md +++ b/zh-cn/device-dev/reference/hdi-apis/_wlan_types_8idl.md @@ -3,8 +3,6 @@ ## **概述** -WLAN模块相关的数据类型。 - WLAN模块中使用的数据类型,包括feature对象信息、STA信息、扫描信息、网络设备信息等。 **Since:** diff --git a/zh-cn/device-dev/reference/hdi-apis/codec__component__type_h.md b/zh-cn/device-dev/reference/hdi-apis/codec__component__type_h.md index 027912d120d337445daa2a14dcece28259b3ebda..b6ddc54e8b1acbe57d7207ef04e78df87a3a85c6 100644 --- a/zh-cn/device-dev/reference/hdi-apis/codec__component__type_h.md +++ b/zh-cn/device-dev/reference/hdi-apis/codec__component__type_h.md @@ -3,7 +3,6 @@ ## **概述** -Codec模块接口定义中使用的自定义数据类型。 Codec模块接口定义中使用的自定义数据类型,包括编解码类型、音视频参数、buffer定义等。 diff --git a/zh-cn/device-dev/reference/hdi-apis/display__type_8h.md b/zh-cn/device-dev/reference/hdi-apis/display__type_8h.md index bfb64ef5202af14af0ea969ce208b19a2d6e0348..bbf2dabaf247dda3f019bb5b8341ee96019e5f2a 100644 --- a/zh-cn/device-dev/reference/hdi-apis/display__type_8h.md +++ b/zh-cn/device-dev/reference/hdi-apis/display__type_8h.md @@ -52,7 +52,7 @@ | 名称 | 描述 | | -------- | -------- | -| [PROPERTY_NAME_LEN](_display.md#propertynamelen)   50 | 属性名字长度。 | +| [PROPERTY_NAME_LEN](_display.md#property_name_len)  50 | 属性名字长度。 | ### 枚举 diff --git a/zh-cn/device-dev/reference/hdi-apis/input__type_8h.md b/zh-cn/device-dev/reference/hdi-apis/input__type_8h.md index 22fd725d29f3777faa610810224f9626ce38fae7..44430e50ce053966b1da33e26c65a5ed9147260e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/input__type_8h.md +++ b/zh-cn/device-dev/reference/hdi-apis/input__type_8h.md @@ -44,17 +44,17 @@ Input设备相关的类型定义。 | 名称 | 描述 | | -------- | -------- | -| [MAX_INPUT_DEV_NUM](input.md#maxinputdevnum)   32 | Input设备数量的最大值。 | -| [CHIP_INFO_LEN](input.md#chipinfolen)   10 | 芯片信息长度。 | -| [CHIP_NAME_LEN](input.md#chipnamelen)   10 | 芯片名称长度。 | -| [VENDOR_NAME_LEN](input.md#vendornamelen)   10 | 厂商名称长度。 | -| [DEV_NAME_LEN](input.md#devnamelen)   64 | Input设备名称长度。 | -| [SELF_TEST_RESULT_LEN](input.md#selftestresultlen)   20 | 自测结果长度。 | -| [DEV_MANAGER_SERVICE_NAME](input.md#devmanagerservicename)   "hdf_input_host" | Input设备节点服务名称。 | -| [DIV_ROUND_UP](input.md#divroundup)(nr, d)   (((nr) + (d) - 1) / (d)) | 向上取整计算公式。 | -| [BYTE_HAS_BITS](input.md#bytehasbits)   8 | 一个字节所包含的比特数。 | -| [BITS_TO_UINT64](input.md#bitstouint64)(count)   [DIV_ROUND_UP](input.md#divroundup)(count, [BYTE_HAS_BITS](input.md#bytehasbits) \* sizeof(uint64_t)) | 比特与64位无符号整数的转换公式。 | -| [HDF_FF_CNT](input.md#hdfffcnt)   (0x7f + 1) | Input设备发送力反馈命令的数量最大值。 | +| [MAX_INPUT_DEV_NUM](input.md#max_input_dev_num)   32 | Input设备数量的最大值。 | +| [CHIP_INFO_LEN](input.md#chip_info_len)   10 | 芯片信息长度。 | +| [CHIP_NAME_LEN](input.md#chip_name_len)   10 | 芯片名称长度。 | +| [VENDOR_NAME_LEN](input.md#vendor_name_len)   10 | 厂商名称长度。 | +| [DEV_NAME_LEN](input.md#dev_name_len)   64 | Input设备名称长度。 | +| [SELF_TEST_RESULT_LEN](input.md#self_test_result_len)   20 | 自测结果长度。 | +| [DEV_MANAGER_SERVICE_NAME](input.md#dev_manager_service_name)   "hdf_input_host" | Input设备节点服务名称。 | +| [DIV_ROUND_UP](input.md#div_round_up)(nr, d)   (((nr) + (d) - 1) / (d)) | 向上取整计算公式。 | +| [BYTE_HAS_BITS](input.md#byte_has_bits)   8 | 一个字节所包含的比特数。 | +| [BITS_TO_UINT64](input.md#bits_to_uint64)(count)   [DIV_ROUND_UP](input.md#div_round_up)(count, [BYTE_HAS_BITS](input.md#byte_has_bits) \* sizeof(uint64_t)) | 比特与64位无符号整数的转换公式。 | +| [HDF_FF_CNT](input.md#hdf_ff_cnt)   (0x7f + 1) | Input设备发送力反馈命令的数量最大值。 | ### 枚举 diff --git a/zh-cn/device-dev/reference/hdi-apis/sensor.md b/zh-cn/device-dev/reference/hdi-apis/sensor.md index 819b16becb94b74508e91dfdd5f560235b1ffe21..5c37da3a27dd00fe925aba5de15f35a8a52d1a88 100644 --- a/zh-cn/device-dev/reference/hdi-apis/sensor.md +++ b/zh-cn/device-dev/reference/hdi-apis/sensor.md @@ -3,9 +3,9 @@ ## **概述** -提供休眠/唤醒操作、订阅休眠/唤醒状态、运行锁管理的接口。 +传感器设备驱动对传感器服务提供通用的接口能力。 -电源模块为电源服务提供的休眠/唤醒操作、订阅休眠/唤醒状态和运行锁管理的接口。 服务获取此模块的对象或代理后,可以调用相关的接口对设备进行休眠/唤醒、订阅休眠/唤醒状态和管理运行锁。 +模块提供传感器服务对传感器驱动访问统一接口,服务获取驱动对象或者代理后,通过其提供的各类方法,以传感器ID区分访问不同类型传感器设备,实现获取传感器设备信息、订阅/取消订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度、量程等可选配置等。 **Since**: @@ -24,7 +24,7 @@ | 名称 | 描述 | | -------- | -------- | | [ISensorCallback.idl](_i_sensor_callback_8idl.md) | Sensor模块为Sensor服务提供数据上报的回调函数。 | -| [ISensorInterface.idl](_i_sensor_interface_8idl.md) | Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/取消订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。 | +| [ISensorInterface.idl](_i_sensor_interface_8idl.md) | Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/取消订阅传感器数据、使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。 | | [SensorTypes.idl](_sensor_types_8idl.md) | 定义传感器模块所使用的传感器类型,传感器信息,传感器数据结构等数据类型。 | 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/figures/HiTraceMeter.png b/zh-cn/device-dev/subsystems/figures/HiTraceMeter.png new file mode 100644 index 0000000000000000000000000000000000000000..15e6c6bc750993801d814bfba775a8f4a0141590 Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/HiTraceMeter.png differ 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-build-module.md b/zh-cn/device-dev/subsystems/subsys-build-module.md index 060c3e8cd1de8b643d28172f663400a785f2512e..07c0b3022f064ca92c99795b200684f510ac7514 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-module.md +++ b/zh-cn/device-dev/subsystems/subsys-build-module.md @@ -25,7 +25,7 @@ ohos_resources #其他常用模板 #配置文件 -ohos_prebuild_etc +ohos_prebuilt_etc #sa配置 ohos_sa_profile diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md b/zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md index 59f3e29fcc1a8725ac1df9c58e897e88277e5f47..b53bc41d2d1bf2f3ec39e65317ae996b9776bb52 100755 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @@ -53,7 +53,7 @@ HiLog是OpenHarmony日志系统,提供给系统框架、服务、以及应用 ``` #undef LOG_DOMAIN #undef LOG_TAG - #define LOG_DOMAIN 0 // 标识业务领域,范围0x0~0xFFFFF + #define LOG_DOMAIN 0xD003200 // 标识业务领域,范围0xD000000~0xD0FFFFF #define LOG_TAG "MY_TAG" ``` @@ -82,7 +82,7 @@ HiLog是OpenHarmony日志系统,提供给系统框架、服务、以及应用 ``` class MyClass { - static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0, "MY_TAG"}; + static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD003200, "MY_TAG"}; ...... } ``` @@ -91,7 +91,7 @@ HiLog是OpenHarmony日志系统,提供给系统框架、服务、以及应用 ``` using namespace OHOS::HiviewDFX; - static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "MY_TAG"}; + static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD003200, "MY_TAG"}; ``` 打印日志: diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md index 11ec506b37867823f6c4e73dae4b7444dba48fe5..c4ac1bf5503818d94237cf12de8f3ce7fe91ce63 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md @@ -76,7 +76,7 @@ HiTraceMeter主要提供抓取用户态和内核态Trace数据的命令行工具 - ![输入图片说明](../../figures/Hitrace.png) +![输入图片说明](figures/HiTraceMeter.png) @@ -108,8 +108,8 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 | Sync trace | 功能描述 |参数说明 | | :----------------------------------------------------------- | ------------- |------------- | -| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | 启动同步trace |label: Trace category。 | -| void FinishTrace(uint64_t label); | 关闭同步trace |value: Trace携带的信息,表明当前的某种状态,例如内存大小,队列长短等。 | +| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | 启动同步trace |label: Trace category。
value: Trace携带的信息,表明当前的某种状态,例如内存大小,队列长短等。 | +| void FinishTrace(uint64_t label); | 关闭同步trace |label: Trace category。 | 同步接口StartTrace和FinishTrace必须配对使用,FinishTrace和前面最近的StartTrace进行匹配。StartTrace和FinishTrace函数对可以嵌套模式使用,跟踪数据解析时使用栈式数据结构进行匹配。接口中的limit参数用于限流,使用默认值即可。 @@ -118,9 +118,8 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 | Async trace | 功能描述 |参数说明 | | ------------------------------------------------------------ | ------------- |------------- | -| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | 开启异步trace | label: Trace category。 | -| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | 关闭异步trace | value: Trace携带的信息,表明当前的某种状态,例如内存大小,队列长短等。| -| | | taskId:异步Trace中用来表示关联的ID。 | +| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | 开启异步trace | label: Trace category。
value: Trace携带的信息,表明当前的某种状态,例如内存大小,队列长短等。
taskId:异步Trace中用来表示关联的ID。 | +| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | 关闭异步trace | label: Trace category。
value: Trace携带的信息,表明当前的某种状态,例如内存大小,队列长短等。
taskId:异步Trace中用来表示关联的ID。 | @@ -130,8 +129,7 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 | Counter Trace | 功能描述 |参数说明 | | ------------------------------------------------------------ | --------- |--------- | -| void CountTrace(uint64_t label, const std::string& name, int64_t); | 计数trace |label: Trace category。。 | -| | |name: Trace的名称,IDE中会以此字段展示这段Trace。 | +| void CountTrace(uint64_t label, const std::string& name, int64_t); | 计数trace |label: Trace category。
name: Trace的名称,IDE中会以此字段展示这段Trace。 | ## 开发步骤 @@ -142,48 +140,24 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 ``` 2. 头文件依赖添加。 - ``` + ```cpp #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的结束点 + + CountTrace(label, "count number", 2000); // 整数跟踪 - sleep(1); - CountTrace(label, "count number", 3000); // 整数跟踪 + StartTrace(label, "func1Trace", -1); // func1Start的跟踪起始点 - 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的结束点 + FinishTrace(label); // func1Trace的结束点 - return 0; - } + StartAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的开始点 + FinishAsyncTrace(label, "asyncTrace2", 3456); // 异步asyncTrace2的结束点 ``` 4. 使用方法,打点编译部署完成后,运行下面命令行来抓取Trace。然后在端侧shell里运行应用,可以抓取到Trace数据。 @@ -194,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。 @@ -235,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", @@ -250,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/device-dev/website.md b/zh-cn/device-dev/website.md index 1fe6576b25b528ca3483740deb6463590ebf4154..f26f2863bbd04c491f1e4ab3b90d6057e057cf9f 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -465,7 +465,7 @@ - [DFX概述](subsystems/subsys-dfx-overview.md) - [HiLog开发指导](subsystems/subsys-dfx-hilog-rich.md) - [HiLog_Lite开发指导](subsystems/subsys-dfx-hilog-lite.md) - - [HiTrace开发指导](subsystems/subsys-dfx-hitrace.md) + - [HiTraceChain开发指导](subsystems/subsys-dfx-hitracechain.md) - [HiCollie开发指导](subsystems/subsys-dfx-hicollie.md) - HiSysEvent开发指导 - [HiSysEvent打点配置指导](subsystems/subsys-dfx-hisysevent-logging-config.md) @@ -539,23 +539,25 @@ - [启动恢复常见问题](faqs/faqs-startup.md) - [系统应用常见问题](faqs/faqs-system-applications.md) - HDI接口参考 - - 模块 + - 模块 - [Audio](reference/hdi-apis/_audio.md) - [Battery](reference/hdi-apis/battery.md) - - [Camera](reference/hdi-apis/_camera.md) - - [Codec](reference/hdi-apis/_codec.md) + - [Camera](reference/hdi-apis/camera.md) + - [Codec](reference/hdi-apis/codec.md) - [Display](reference/hdi-apis/_display.md) - [HdfFaceAuth](reference/hdi-apis/_hdf_face_auth.md) - - [Input](reference/hdi-apis/_input.md) - - [Light](reference/hdi-apis/_light.md) - [HdfPinAuth](reference/hdi-apis/_hdf_pin_auth.md) + - [HdfUserAuth](reference/hdi-apis/_hdf_user_auth.md) + - [HdiActivityRecognition](reference/hdi-apis/activity_recognition.md) + - [Input](reference/hdi-apis/input.md) + - [Light](reference/hdi-apis/light.md) + - [Motion](reference/hdi-apis/motion.md) - [Power](reference/hdi-apis/power.md) - - [Sensor](reference/hdi-apis/_sensor.md) + - [Sensor](reference/hdi-apis/sensor.md) - [Thermal](reference/hdi-apis/thermal.md) - - [USB](reference/hdi-apis/_u_s_b.md) - - [HdfUserAuth](reference/hdi-apis/_hdf_user_auth.md) - - [Vibrator](reference/hdi-apis/_vibrator.md) - - [WLAN](reference/hdi-apis/_w_l_a_n.md) + - [USB](reference/hdi-apis/usb.md) + - [Vibrator](reference/hdi-apis/vibrator.md) + - [WLAN](reference/hdi-apis/wlan.md) - 头文件和结构体 - 头文件 - [audio_adapter.h](reference/hdi-apis/audio__adapter_8h.md) @@ -567,65 +569,74 @@ - [audio_scene.h](reference/hdi-apis/audio__scene_8h.md) - [audio_types.h](reference/hdi-apis/audio__types_8h.md) - [audio_volume.h](reference/hdi-apis/audio__volume_8h.md) - - [codec_callback_if.h](reference/hdi-apis/codec__callback__if_8h.md) - - [codec_common_type.h](reference/hdi-apis/codec__common__type_8h.md) - - [codec_component_if.h](reference/hdi-apis/codec__component__if_8h.md) - - [codec_component_manager.h](reference/hdi-apis/codec__component__manager_8h.md) - - [codec_component_type.h](reference/hdi-apis/codec__component__type_8h.md) + - [codec_callback_if.h](reference/hdi-apis/codec_callback_if_h.md) + - [codec_common_type.h](reference/hdi-apis/codec_common_type_h.md) + - [codec_component_if.h](reference/hdi-apis/codec_component_if_h.md) + - [codec_component_manager.h](reference/hdi-apis/codec__component__manager_h.md) + - [codec_component_type.h](reference/hdi-apis/codec__component__type_h.md) - [display_device.h](reference/hdi-apis/display__device_8h.md) - [display_gfx.h](reference/hdi-apis/display__gfx_8h.md) - [display_gralloc.h](reference/hdi-apis/display__gralloc_8h.md) - [display_layer.h](reference/hdi-apis/display__layer_8h.md) - [display_type.h](reference/hdi-apis/display__type_8h.md) - - [icamera_device_callback.h](reference/hdi-apis/icamera__device__callback_8h.md) - - [icamera_device.h](reference/hdi-apis/icamera__device_8h.md) - - [icamera_host_callback.h](reference/hdi-apis/icamera__host__callback_8h.md) - - [icamera_host.h](reference/hdi-apis/icamera__host_8h.md) + - [display_vgu.h](reference/hdi-apis/display__vgu_8h.md) - [input_controller.h](reference/hdi-apis/input__controller_8h.md) - [input_manager.h](reference/hdi-apis/input__manager_8h.md) - [input_reporter.h](reference/hdi-apis/input__reporter_8h.md) - [input_type.h](reference/hdi-apis/input__type_8h.md) - - [ioffline_stream_operator.h](reference/hdi-apis/ioffline__stream__operator_8h.md) - - [istream_operator_callback.h](reference/hdi-apis/istream__operator__callback_8h.md) - - [istream_operator.h](reference/hdi-apis/istream__operator_8h.md) - - [light_if.h](reference/hdi-apis/light__if_8h.md) - - [light_type.h](reference/hdi-apis/light_8typeh.md) - - [sensor_if.h](reference/hdi-apis/sensor__if_8h.md) - - [sensor_type.h](reference/hdi-apis/sensor__type_8h.md) - - [types.h](reference/hdi-apis/types_8h.md) - - [usb_info.h](reference/hdi-apis/usb__info_8h.md) - - [usbd_client.h](reference/hdi-apis/usbd__client_8h.md) - - [usbd_subscriber.h](reference/hdi-apis/usbd__subscriber_8h.md) - - [usbd_type.h](reference/hdi-apis/usbd__type_8h.md) - - [vibrator_if.h](reference/hdi-apis/vibrator__if_8h.md) - - [vibrator_type.h](reference/hdi-apis/vibrator__type_8h.md) - - [wifi_hal_ap_feature.h](reference/hdi-apis/wifi__hal__ap__feature_8h.md) - - [wifi_hal_base_feature.h](reference/hdi-apis/wifi__hal__base__feature_8h.md) - - [wifi_hal_sta_feature.h](reference/hdi-apis/wifi__hal__sta__feature_8h.md) - - [wifi_hal.h](reference/hdi-apis/wifi__hal_8h.md) + - [ActivityRecognitionTypes.idl](reference/hdi-apis/activity_recognition_types_idl.md) + - [Types.idl](reference/hdi-apis/battery_types_idl.md) - [IExecutor.idl](reference/hdi-apis/face__auth_2_i_executor_8idl.md) - [IExecutorCallback.idl](reference/hdi-apis/face__auth_2_i_executor_callback_8idl.md) - [FaceAuthTypes.idl](reference/hdi-apis/_face_auth_types_8idl.md) - [PinAuthTypes.idl](reference/hdi-apis/_pin_auth_types_8idl.md) - - [IBatteryCallback.idl](reference/hdi-apis/_i_battery_callback_8idl.md) - - [IBatteryInterface.idl](reference/hdi-apis/_i_battery_interface_8idl.md) - [IExecutor.idl](reference/hdi-apis/pin__auth_2_i_executor_8idl.md) - [IExecutorCallback.idl](reference/hdi-apis/pin__auth_2_i_executor_callback_8idl.md) - [IFaceAuthInterface.idl](reference/hdi-apis/_i_face_auth_interface_8idl.md) - [IPinAuthInterface.idl](reference/hdi-apis/_i_pin_auth_interface_8idl.md) + - [IUserAuthInterface.idl](reference/hdi-apis/_i_user_auth_interface_8idl.md) + - [UserAuthTypes.idl](reference/hdi-apis/_user_auth_types_8idl.md) + - [IActivityChangedCallback.idl](reference/hdi-apis/_i_activity_changed_callback_8idl.md) + - [IActivityInterface.idl](reference/hdi-apis/_i_activity_interface_8idl.md) + - [IBatteryCallback.idl](reference/hdi-apis/_i_battery_callback_8idl.md) + - [IBatteryInterface.idl](reference/hdi-apis/_i_battery_interface_8idl.md) + - [ICameraDevice.idl](reference/hdi-apis/_i_camera_device_8idl.md) + - [ICameraDeviceCallback.idl](reference/hdi-apis/_i_camera_device_callback_8idl.md) + - [ICameraHostCallback.idl](reference/hdi-apis/_i_camera_host_callback_8idl.md) + - [ICameraHost.idl](reference/hdi-apis/_i_camera_host_8idl.md) + - [ILightInterface.idl](reference/hdi-apis/_i_light_interface_8idl.md) + - [IMotionCallback.idl](reference/hdi-apis/_i_motion_callback_8idl.md) + - [IMotionInterface.idl](reference/hdi-apis/_i_motion_interface_8idl.md) + - [IOfflineStreamOperator.idl](reference/hdi-apis/_i_offline_stream_operator_8idl.md) - [IPowerHdiCallback.idl](reference/hdi-apis/_i_power_hdi_callback_8idl.md) - [IPowerInterface.idl](reference/hdi-apis/_i_power_interface_8idl.md) - - [IThermalInterface.idl](reference/hdi-apis/_i_thermal_interface_8idl.md) + - [ISensorCallback.idl](reference/hdi-apis/_i_sensor_callback_8idl.md) + - [ISensorInterface.idl](reference/hdi-apis/_i_sensor_interface_8idl.md) + - [IStreamOperator.idl](reference/hdi-apis/_i_stream_operator_8idl.md) + - [IStreamOperatorCallback.idl](reference/hdi-apis/_i_stream_operator_callback_8idl.md) - [IThermalCallback.idl](reference/hdi-apis/_i_thermal_callback_8idl.md) - - [IUserAuthInterface.idl](reference/hdi-apis/_i_user_auth_interface_8idl.md) + - [IThermalInterface.idl](reference/hdi-apis/_i_thermal_interface_8idl.md) + - [IUsbdBulkCallback.idl](reference/hdi-apis/_i_usbd_bulk_callback_8idl.md) + - [IUsbInterface.idl](reference/hdi-apis/_i_usb_interface_8idl.md) + - [IUsbdSubscriber.idl](reference/hdi-apis/_i_usbd_subscriber_8idl.md) + - [IVibratorInterface.idl](reference/hdi-apis/_i_vibrator_interface_8idl.md) + - [IWlanCallback.idl](reference/hdi-apis/_i_wlan_callback_8idl.md) + - [IWlanInterface.idl](reference/hdi-apis/_i_wlan_interface_8idl.md) + - [LightTypes.idl](reference/hdi-apis/_light_types_8idl.md) + - [MotionTypes.idl](reference/hdi-apis/_motion_types_8idl.md) - [PowerTypes.idl](reference/hdi-apis/_power_types_8idl.md) + - [SensorTypes.idl](reference/hdi-apis/_sensor_types_8idl.md) - [ThermalTypes.idl](reference/hdi-apis/_thermal_types_8idl.md) - - [Types.idl](reference/hdi-apis/_types_8idl.md) - - [UserAuthTypes.idl](reference/hdi-apis/_user_auth_types_8idl.md) + - [Types.idl](reference/hdi-apis/camera_2v1__0_2_types_8idl.md) + - [UsbTypes.idl](reference/hdi-apis/_usb_types_8idl.md) + - [VibratorTypes.idl](reference/hdi-apis/_vibrator_types_8idl.md) + - [WlanTypes.idl](reference/hdi-apis/_wlan_types_8idl.md) - 结构体 - - [attribute](reference/hdi-apis/____attribute____.md) - - [Alignment](reference/hdi-apis/_alignment.md) + - [YUVDescInfo](reference/hdi-apis/_yun_desc_info_.md) + - [ExtDataHandle](reference/hdi-apis/_ext_data_handle.md) + - [ActRecognitionEvent](reference/hdi-apis/_act_recognition_event.md) - [AllocInfo](reference/hdi-apis/_alloc_info.md) + - [Alignment](reference/hdi-apis/_alignment.md) - [AudioAdapter](reference/hdi-apis/_audio_adapter.md) - [AudioAdapterDescriptor](reference/hdi-apis/_audio_adapter_descriptor.md) - [AudioAttribute](reference/hdi-apis/_audio_attribute.md) @@ -637,7 +648,7 @@ - [AudioMixExtInfo](reference/hdi-apis/_audio_mix_ext_info.md) - [AudioMmapBufferDescripter](reference/hdi-apis/_audio_mmap_buffer_descripter.md) - [AudioPort](reference/hdi-apis/_audio_port.md) - - [AudioPortCap](reference/hdi-apis/_audio_port_cap.md) + - [AudioPortCap](reference/hdi-apis/audio_portcap.md) - [AudioPortCapability](reference/hdi-apis/_audio_port_capability.md) - [AudioRender](reference/hdi-apis/_audio_render.md) - [AudioRoute](reference/hdi-apis/_audio_route.md) @@ -652,12 +663,16 @@ - [AudioVolume](reference/hdi-apis/_audio_volume.md) - [AuthResultInfo](reference/hdi-apis/_auth_result_info.md) - [AuthSolution](reference/hdi-apis/_auth_solution.md) - - [BatteryInfo](reference/hdi-apis/_battery_info.md) - [BufferData](reference/hdi-apis/_buffer_data.md) + - [BatteryInfo](reference/hdi-apis/_battery_info.md) + - [CaptureEndedInfo](reference/hdi-apis/_capture_ended_info.md) + - [CaptureErrorInfo](reference/hdi-apis/_capture_error_info.md) + - [CaptureInfo](reference/hdi-apis/_capture_info.md) - [CodecCallbackType](reference/hdi-apis/_codec_callback_type.md) - [CodecCompCapability](reference/hdi-apis/_codec_comp_capability.md) - [CodecComponentManager](reference/hdi-apis/_codec_component_manager.md) - [CodecComponentType](reference/hdi-apis/_codec_component_type.md) + - [ColorValue](reference/hdi-apis/union_color_value.md) - [CompVerInfo](reference/hdi-apis/_comp_ver_info.md) - [CredentialInfo](reference/hdi-apis/_credential_info.md) - [DeviceFuncs](reference/hdi-apis/_device_funcs.md) @@ -676,11 +691,33 @@ - [GfxFuncs](reference/hdi-apis/_gfx_funcs.md) - [GfxOpt](reference/hdi-apis/_gfx_opt.md) - [GrallocFuncs](reference/hdi-apis/_gralloc_funcs.md) + - [HdfFeatureInfo](reference/hdi-apis/_hdf_feature_info.md) + - [HdfLightColor](reference/hdi-apis/_hdf_light_color.md) + - [HdfLightEffect](reference/hdi-apis/_hdf_light_effect.md) + - [HdfLightFlashEffect](reference/hdi-apis/_hdf_light_flash_effect.md) + - [HdfLightInfo](reference/hdi-apis/_hdf_light_info.md) + - [HdfMotionEvent](reference/hdi-apis/_hdf_motion_event.md) + - [HdfNetDeviceInfo](reference/hdi-apis/_hdf_net_device_info.md) + - [HdfNetDeviceInfoResult](reference/hdi-apis/_hdf_net_device_info_result.md) + - [HdfSensorEvents](reference/hdi-apis/_hdf_sensor_events.md) + - [HdfSensorInformation](reference/hdi-apis/_hdf_sensor_information.md) + - [HdfStaInfo](reference/hdi-apis/_hdf_sta_info.md) - [HdfThermalCallbackInfo](reference/hdi-apis/_hdf_thermal_callback_info.md) + - [HdfVibratorInfo](reference/hdi-apis/_hdf_vibrator_info.md) + - [HdfWifiDriverScanSsid](reference/hdi-apis/_hdf_wifi_driver_scan_ssid.md) + - [HdfWifiInfo](reference/hdi-apis/_hdf_wifi_info.md) + - [HdfWifiScan](reference/hdi-apis/_hdf_wifi_scan.md) + - [HdfWifiScanResult](reference/hdi-apis/_hdf_wifi_scan_result.md) - [HDRCapability](reference/hdi-apis/_h_d_r_capability.md) - [HDRMetaData](reference/hdi-apis/_h_d_r_meta_data.md) + - [IActivityChangedCallback](reference/hdi-apis/interface_i_activity_changed_callback.md) + - [IActivityInterface](reference/hdi-apis/interface_i_activity_interface.md) - [IBatteryCallback](reference/hdi-apis/interface_i_battery_callback.md) - [IBatteryInterface](reference/hdi-apis/interface_i_battery_interface.md) + - [ICameraDevice](reference/hdi-apis/interface_i_camera_device.md) + - [ICameraDeviceCallback](reference/hdi-apis/interface_i_camera_device_callback.md) + - [ICameraHost](reference/hdi-apis/interface_i_camera_host.md) + - [ICameraHostCallback](reference/hdi-apis/interface_i_camera_host_callback.md) - [ICircle](reference/hdi-apis/_i_circle.md) - [IdentifyResultInfo](reference/hdi-apis/_identify_result_info.md) - [IExecutor](reference/hdi-apis/interface_i_executor.md) @@ -688,80 +725,95 @@ - [IExecutorCallback](reference/hdi-apis/interface_i_executor_callback.md) - [IExecutorCallback](reference/hdi-apis/interface_pin_i_executor_callback.md) - [IFaceAuthInterface](reference/hdi-apis/interface_i_face_auth_interface.md) - - [IInputInterface](reference/hdi-apis/_i_input_interface.md) - [ILine](reference/hdi-apis/_i_line.md) + - [IInputInterface](reference/hdi-apis/_i_input_interface.md) + - [ILightInterface](reference/hdi-apis/interface_i_light_interface.md) + - [IMotionCallback](reference/hdi-apis/interface_i_motion_callback.md) + - [IMotionInterface](reference/hdi-apis/interface_i_motion_interface.md) - [InputController](reference/hdi-apis/_input_controller.md) - [InputDevAbility](reference/hdi-apis/_input_dev_ability.md) - - [InputDevAttr](reference/hdi-apis/_input_dev_attr.md) + - [InputDevAttr](reference/hdi-apis/_input_dev_attr.md) - [InputDevDesc](reference/hdi-apis/_input_dev_desc.md) + - [InputDeviceInfo](reference/hdi-apis/_input_device_info.md) - [InputDevIdentify](reference/hdi-apis/_input_dev_identify.md) - - [InputDeviceInfo](reference/hdi-apis/_device_info.md) - - [InputDimensionInfo](reference/hdi-apis/_input_dimension_info.md) - - [InputEventCb](reference/hdi-apis/_input_report_event_cb.md) - - [InputEventPackage](reference/hdi-apis/_event_package.md) + - [InputDimensionInfo](reference/hdi-apis/_input_dimension_info.md) + - [InputEventCb](reference/hdi-apis/_input_event_cb.md) + - [InputEventPackage](reference/hdi-apis/_input_event_package.md) + - [IPowerHdiCallback](reference/hdi-apis/interface_i_power_hdi_callback.md) - [InputExtraCmd](reference/hdi-apis/_input_extra_cmd.md) - [InputHostCb](reference/hdi-apis/_input_host_cb.md) - - [InputHotPlugEvent](reference/hdi-apis/_input_hotplug_event.md) + - [InputHotPlugEvent](reference/hdi-apis/_input_hot_plug_event.md) - [InputManager](reference/hdi-apis/_input_manager.md) - [InputReporter](reference/hdi-apis/_input_reporter.md) + - [IOfflineStreamOperator](reference/hdi-apis/interface_i_offline_stream_operator.md) - [IPinAuthInterface](reference/hdi-apis/interface_i_pin_auth_interface.md) - - [IPowerHdiCallback](reference/hdi-apis/interface_i_power_hdi_callback.md) - [IPowerInterface](reference/hdi-apis/interface_i_power_interface.md) - [IRect](reference/hdi-apis/_i_rect.md) + - [ISensorCallback](reference/hdi-apis/interface_i_sensor_callback.md) + - [ISensorInterface](reference/hdi-apis/interface_i_sensor_interface.md) + - [IStreamOperator](reference/hdi-apis/interface_i_stream_operator.md) + - [IStreamOperatorCallback](reference/hdi-apis/interface_i_stream_operator_callback.md) - [ISurface](reference/hdi-apis/_i_surface.md) - [IThermalCallback](reference/hdi-apis/interface_i_thermal_callback.md) - [IThermalInterface](reference/hdi-apis/interface_i_thermal_interface.md) + - [IUsbdBulkCallback](reference/hdi-apis/interface_i_usbd_bulk_callback.md) + - [IUsbdSubscriber](reference/hdi-apis/interface_i_usbd_subscriber.md) + - [IUsbInterface](reference/hdi-apis/interface_i_usb_interface.md) - [IUserAuthInterface](reference/hdi-apis/interface_i_user_auth_interface.md) - - [IWiFi](reference/hdi-apis/_i_wi_fi.md) - - [IWiFiAp](reference/hdi-apis/_i_wi_fi_ap.md) - - [IWiFiBaseFeature](reference/hdi-apis/_i_wi_fi_base_feature.md) - - [IWiFiSta](reference/hdi-apis/_i_wi_fi_sta.md) + - [IVibratorInterface](reference/hdi-apis/interface_i_vibrator_interface.md) + - [IWlanCallback](reference/hdi-apis/interface_i_wlan_callback.md) + - [IWlanInterface](reference/hdi-apis/interface_i_wlan_interface.md) - [LayerAlpha](reference/hdi-apis/_layer_alpha.md) - [LayerBuffer](reference/hdi-apis/_layer_buffer.md) - [LayerFuncs](reference/hdi-apis/_layer_funcs.md) - [LayerInfo](reference/hdi-apis/_layer_info.md) - - [LightEffect](reference/hdi-apis/_light_effect.md) - - [LightFlashEffect](reference/hdi-apis/_light_flash_effect.md) - - [LightInfo](reference/hdi-apis/_light_info.md) - - [LightInterface](reference/hdi-apis/_light_interface.md) - - [OHOS::Camera::CaptureEndedInfo](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md) - - [OHOS::Camera::CaptureErrorInfo](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_error_info.md) - - [OHOS::Camera::CaptureInfo](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md) - - [OHOS::Camera::ICameraDevice](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_camera_device.md) - - [OHOS::Camera::ICameraDeviceCallback](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_camera_device_callback.md) - - [OHOS::Camera::ICameraHost](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_camera_host.md) - - [OHOS::Camera::ICameraHostCallback](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_camera_host_callback.md) - - [OHOS::Camera::IOfflineStreamOperator](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_offline_stream_operator.md) - - [OHOS::Camera::IStreamOperator](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_stream_operator.md) - - [OHOS::Camera::IStreamOperatorCallback](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_i_stream_operator_callback.md) - - [OHOS::Camera::StreamAttribute](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_stream_attribute.md) - - [OHOS::Camera::StreamInfo](reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_stream_info.md) - - [OHOS::USB::UsbCtrlTransfer](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usb_ctrl_transfer.md) - - [OHOS::USB::UsbdClient](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md) - - [OHOS::USB::UsbDev](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usb_dev.md) - - [OHOS::USB::USBDeviceInfo](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_u_s_b_device_info.md) - - [OHOS::USB::UsbdSubscriber](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_subscriber.md) - - [OHOS::USB::UsbInfo](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usb_info.md) - - [OHOS::USB::UsbPipe](reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usb_pipe.md) + - [MeasChannelParam](reference/hdi-apis/_meas_channel_param.md) + - [MeasChannelResult](reference/hdi-apis/_meas_channel_result.md) - [OmxCodecBuffer](reference/hdi-apis/_omx_codec_buffer.md) - [PortCap](reference/hdi-apis/union_port_cap.md) + - [PortInfo](reference/hdi-apis/_port_info.md) - [PresentTimestamp](reference/hdi-apis/_present_timestamp.md) - [PropertyObject](reference/hdi-apis/_property_object.md) + - [ProjectionScreenCmdParam](reference/hdi-apis/_projection_screen_cmd_param.md) - [RangeValue](reference/hdi-apis/_range_value.md) - [Rect](reference/hdi-apis/_rect.md) - [Rectangle](reference/hdi-apis/_rectangle.md) + - [RGBColor](reference/hdi-apis/_r_g_b_color.md) - [ScheduleInfo](reference/hdi-apis/_schedule_info.md) - - [SensorEvents](reference/hdi-apis/_sensor_events.md) - - [SensorInformation](reference/hdi-apis/_sensor_information.md) - - [SensorInterface](reference/hdi-apis/_sensor_interface.md) - - [StaInfo](reference/hdi-apis/_sta_info.md) + - [StreamAttribute](reference/hdi-apis/_stream_attribute.md) + - [StreamInfo](reference/hdi-apis/_stream_info.md) - [SupportBufferType](reference/hdi-apis/_support_buffer_type.md) - [TemplateInfo](reference/hdi-apis/_template_info.md) - [ThermalZoneInfo](reference/hdi-apis/_thermal_zone_info.md) + - [UsbCtrlTransfer](reference/hdi-apis/_usb_ctrl_transfer.md) + - [UsbDev](reference/hdi-apis/_usb_dev.md) + - [USBDeviceInfo](reference/hdi-apis/_u_s_b_device_info.md) + - [UsbPipe](reference/hdi-apis/_usb_pipe.md) - [UseBufferType](reference/hdi-apis/_use_buffer_type.md) - [VerifyAllocInfo](reference/hdi-apis/_verify_alloc_info.md) - - [VibratorInterface](reference/hdi-apis/_vibrator_interface.md) + - [VGUBuffer](reference/hdi-apis/_v_g_u_buffer.md) + - [VGUColorStop](reference/hdi-apis/_v_g_u_color_stop.md) + - [VGUConic](reference/hdi-apis/_v_g_u_conic.md) + - [VGUFillAttr](reference/hdi-apis/_v_g_u_fill_attr.md) + - [VGUFuncs](reference/hdi-apis/_v_g_u_funcs.md) + - [VGUGradient](reference/hdi-apis/_v_g_u_gradient.md) + - [VGUImage](reference/hdi-apis/_v_g_u_image.md) + - [VGULinear](reference/hdi-apis/_v_g_u_linear.md) + - [VGUMaskLayer](reference/hdi-apis/_v_g_u_mask_layer.md) + - [VGUMatrix3](reference/hdi-apis/_v_g_u_matrix3.md) + - [VGUPaintStyle](reference/hdi-apis/_v_g_u_paint_style.md) + - [VGUPath](reference/hdi-apis/_v_g_u_path.md) + - [VGUPattern](reference/hdi-apis/_v_g_u_pattern.md) + - [VGUPoint](reference/hdi-apis/_v_g_u_point.md) + - [VGURadial](reference/hdi-apis/_v_g_u_radial.md) + - [VGURect](reference/hdi-apis/_v_g_u_rect.md) + - [VGUSolid](reference/hdi-apis/_v_g_u_solid.md) + - [VGUStrokeAttr](reference/hdi-apis/_v_g_u_stroke_attr.md) + - [VGUSurface](reference/hdi-apis/_v_g_u_surface.md) - [VideoPortCap](reference/hdi-apis/_video_port_cap.md) + - [WifiStationInfo](reference/hdi-apis/_wifi_station_info.md) + - [WRGBColor](reference/hdi-apis/_w_r_g_b_color.md) + - CMSIS API参考 - [CMSIS](reference/kernel/cmsis/_c_m_s_i_s-_r_t_o_s.md) diff --git a/zh-cn/figures/Hitrace.png b/zh-cn/figures/Hitrace.png deleted file mode 100644 index 258d0c9d7b5b95b9d10072b9771bc6f761be3c7b..0000000000000000000000000000000000000000 Binary files a/zh-cn/figures/Hitrace.png and /dev/null differ diff --git a/zh-cn/figures/hitrace.png b/zh-cn/figures/hitrace.png deleted file mode 100644 index e9f5ac4d22acc96f6bb0d163405367c50689b90e..0000000000000000000000000000000000000000 Binary files a/zh-cn/figures/hitrace.png and /dev/null differ 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/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md new file mode 100644 index 0000000000000000000000000000000000000000..4c7289ed1c70c6171775bf34f9701689e94e5792 --- /dev/null +++ b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md @@ -0,0 +1,21 @@ +# 3.1 release相对于3.1 beta变更详细说明 + +### 针对color.json中颜色值,增加合法性校验 + +针对color.json中颜色值,增加合法性校验,其校验规则如下: + +- 使用十六进制颜色码,格式如下: + - #rgb:red(0-f) green(0-f) blue(0-f) + - #argb:transparency(0-f) red(0-f) green(0-f) blue(0-f) + - #rrggbb: red(00-ff) green(00-ff) blue(00-ff) + - #aarrggbb: transparency(00-ff) red(00-ff) green(00-ff) blue(00-ff) +- 使用$引用应用中已定义的资源,格式如下: + - $color:xxx + +**变更影响** + +不符合上述校验规则,将在编译时报错。 + +**关键的接口/组件变更** + +无 \ No newline at end of file diff --git a/zh-cn/release-notes/api-change/v3.1-Release/readme.md b/zh-cn/release-notes/api-change/v3.1-Release/readme.md index ca69ac422e485e04f319ae9dcddabf66012a99dd..6c1ca7ef961568d5b08f3d6b8eb91f83b3dc47db 100644 --- a/zh-cn/release-notes/api-change/v3.1-Release/readme.md +++ b/zh-cn/release-notes/api-change/v3.1-Release/readme.md @@ -4,7 +4,7 @@ - [JS API差异报告](js-apidiff-v3.1-release.md) - [Native API差异报告](native-apidiff-v3.1-release.md) +- [3.1 release相对于3.1 beta变更详细说明](changelog-v3.1-release.md) 此外,本次还发布了OpenHarmony 3.2 Canary (API Version 9 Canary)版本: [JS API差异报告(API Version 9 Canary)](js-apidiff-v3.2-canary.md) - diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md index be343a20c26f3c876661d0f0adfdf898f48a6ada..48b3fb3ed9d96a59e63451b2aa1010d5298c3cda 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md @@ -171,3 +171,25 @@ FA模型下的公共模块变量共享之前是作为需求交付的,在中间 **关键的接口/组件变更** 无 + +## 全球化子系统 + +### 针对color.json中颜色值,增加合法性校验 + +针对color.json中颜色值,增加合法性校验,其校验规则如下: + +- 使用十六进制颜色码,格式如下: + - #rgb:red(0-f) green(0-f) blue(0-f) + - #argb:transparency(0-f) red(0-f) green(0-f) blue(0-f) + - #rrggbb: red(00-ff) green(00-ff) blue(00-ff) + - #aarrggbb: transparency(00-ff) red(00-ff) green(00-ff) blue(00-ff) +- 使用$引用应用中已定义的资源,格式如下: + - $color:xxx + +**变更影响** + +不符合上述校验规则,将在编译时报错。 + +**关键的接口/组件变更** + +无 \ No newline at end of file diff --git a/zh-cn/website.md b/zh-cn/website.md index 9aeef749ffd4e3fbdb266cf7d4457172b3c66fef..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 @@ -155,6 +159,7 @@ - [资源调度](release-notes/api-change/v3.1-Release/js-apidiff-resource-scheduler_api-9-canary.md) - [窗口管理](release-notes/api-change/v3.1-Release/js-apidiff-window_api-9-canary.md) - [Native API差异报告](release-notes/api-change/v3.1-Release/native-apidiff-v3.1-release.md) + - [3.1 release相对于3.1 beta变更详细说明](release-notes/api-change/v3.1-Release/changelog-v3.1-release.md) - OpenHarmony 3.1 Beta - [JS API差异报告](release-notes/api-change/v3.1-beta/js-apidiff-v3.1-beta.md) - [Native API差异报告](release-notes/api-change/v3.1-beta/native-apidiff-v3.1-beta.md)