diff --git a/CODEOWNERS b/CODEOWNERS index 4f7ab1dad900229e988205402075da217e03f536..b3a89aecb5c1bf1907db23aabcb7d61adecc8ab3 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984 zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw @@ -520,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids -zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang @@ -528,8 +529,13 @@ zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCreas zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @liuzuming @ningningW @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515 diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index 594fb355e417b047d93b1de9d413540a2c839190..a8dbb1b636a19fe6a2b7e6dee741b56dac0e6289 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -127,7 +127,7 @@ The following table describes the subsystems of OpenHarmony. For details about t | Build | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems | | Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase.| All systems | | Data Management | Provides local data management and distributed data management:
- Local application data management for lightweight preference databases and relational databases
- Distributed data service to provide applications with the capability to store data in the databases of different devices| Standard system | -| Programming Language Runtime| Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems | +| Compiler and Runtime | Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems | | Distributed Scheduler| Starts, registers, queries, and manages system services. | All systems | | JS UI Framework | OpenHarmony JS UI framework supports web-development-like paradigm. | All systems | | Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables applications to use multimedia resources of the system.| All systems | diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index a627e1116a792c5d4fc885ae01aa6ccb172b7b1d..73bbd2d608562535e3272c1a659bcebbd39b125a 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -17,7 +17,6 @@ - Application Package Structure - [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md) - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) - - [HAR File Structure](quick-start/har-structure.md) - Multi-HAP Mechanism - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) - [Multi-HAP Build View](quick-start/multi-hap-build-view.md) @@ -49,7 +48,7 @@ - Development - [Application Models](application-models/Readme-EN.md) - [UI Development](ui/Readme-EN.md) - - [Common Event and Notification](notification/Readme-EN.md) + - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md) - [Media](media/Readme-EN.md) @@ -57,7 +56,7 @@ - [Connectivity](connectivity/Readme-EN.md) - [Data Management](database/Readme-EN.md) - [File Management](file-management/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) + - [Telephony Service](telephony/Readme-EN.md) - [Task Management](task-management/Readme-EN.md) - [Device Management](device/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) diff --git a/en/application-dev/ability-deprecated/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md index 1340e72918e141dd3b95b5ddc8dbc11258f83493..79cae1da5611b0736f7d11a5bb0cfb9b48df3f0a 100644 --- a/en/application-dev/ability-deprecated/context-userguide.md +++ b/en/application-dev/ability-deprecated/context-userguide.md @@ -250,9 +250,9 @@ In the stage model, in the onWindowStageCreate lifecycle of an ability, you can Use the API described in the table below to obtain the context associated with an ArkTS page. -| API | Description | -| :------------------------------------ | :--------------------------- | -| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.| +| API | Description | +| :------------------------------------ | :----------------------------------------------------------- | +| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.
Since API version 9, this API is supported in ArkTS widgets.| **Example** diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 96e956f86e1528c5946c094b204c83e6e7d96222..ca206e65fd11a48631e950f26c1c9b656f298e13 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: -- [Common Event and Notification](notification/Readme-EN.md) +- [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md) - [Media](media/Readme-EN.md) - [Security](security/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md) -- [Telephony](telephony/Readme-EN.md) +- [Telephony Service](telephony/Readme-EN.md) - [Data Management](database/Readme-EN.md) - [Task Management](task-management/Readme-EN.md) - [Device Management](device/Readme-EN.md) @@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli - [Application Test](application-test/Readme-EN.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md) +- [File Management](file-management/medialibrary-overview.md) ### Tools diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 650eaf0b956e544bd19e8892b0c6946a6839beb5..c7b49ac56b0638e8c4ba9908582683f9c4c46d21 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: -- [Common Event and Notification](notification/notification-overview.md) +- [Notification](notification/notification-overview.md) - [Window Manager](windowmanager/window-overview.md) - [WebGL](webgl/webgl-overview.md) - [Media](media/audio-overview.md) - [Security](security/userauth-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md) -- [Telephony](telephony/telephony-overview.md) +- [Telephony Service](telephony/telephony-overview.md) - [Data Management](database/database-mdds-overview.md) - [Task Management](task-management/background-task-overview.md) - [Device](device/usb-overview.md) @@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli - [Application Test](application-test/arkxtest-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md) +- [File Management](file-management/medialibrary-overview.md) ### Tools diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index efc515db54971c76432f02b5f409990ecbd767b7..2c1505fc1c12e57a96f22fcda7faf92ba9ea7418 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -17,9 +17,12 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](extensionability-overview.md) - [ServiceExtensionAbility](serviceextensionability.md) - - [DataShareExtensionAbility](datashareextensionability.md) + - [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md) - [FormExtensionAbility (Widget)](widget-development-stage.md) - - [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md) + - [AccessibilityExtensionAbility](accessibilityextensionability.md) + - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) + - [InputMethodExtensionAbility](inputmethodextentionability.md) + - [WindowExtensionAbility](windowextensionability.md) - [AbilityStage Component Container](abilitystage.md) - [Context](application-context-stage.md) - Want @@ -32,15 +35,19 @@ - [Component Startup Rules](component-startup-rules.md) - Inter-Device Application Component Interaction (Continuation) - [Continuation Overview](inter-device-interaction-hop-overview.md) - - [Cross-Device Migration](hop-cross-device-migration.md) - - [Multi-device Collaboration](hop-multi-device-collaboration.md) + - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md) + - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md) + - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - IPC - [Process Model](process-model-stage.md) - Common Events - [Introduction to Common Events](common-event-overview.md) - - [Subscribing to Common Events](common-event-subscription.md) - - [Publishing Common Events](common-event-publish.md) + - Common Event Subscription + - [Common Event Subscription Overview](common-event-subscription-overview.md) + - [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md) + - [Subscribing to Common Events in Static Mode (for System Applications Only)](common-event-static-subscription.md) - [Unsubscribing from Common Events](common-event-unsubscription.md) + - [Publishing Common Events](common-event-publish.md) - [Background Services](background-services.md) - Inter-Thread Communication - [Thread Model](thread-model-stage.md) @@ -50,6 +57,7 @@ - [Mission Management Scenarios](mission-management-overview.md) - [Mission Management and Launch Type](mission-management-launch-type.md) - [Page Stack and MissionList](page-mission-stack.md) + - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Application Configuration File](config-file-stage.md) - FA Model Development - [FA Model Development Overview](fa-model-development-overview.md) @@ -63,7 +71,7 @@ - [Creating a PageAbility](create-pageability.md) - [Starting a Local PageAbility](start-local-pageability.md) - [Stopping a PageAbility](stop-pageability.md) - - [Starting a Remote PageAbility](start-remote-pageability.md) + - [Starting a Remote PageAbility (for System Applications Only)](start-remote-pageability.md) - [Starting a Specified Page](start-page.md) - [Window Properties](window-properties.md) - [Requesting Permissions](request-permissions.md) diff --git a/en/application-dev/application-models/ability-startup-with-explicit-want.md b/en/application-dev/application-models/ability-startup-with-explicit-want.md index 9186379f32299ee7a42b7f82af4fc7f464c160d1..6b61b06311a519e959e87d826e4a27c8b2b3d208 100644 --- a/en/application-dev/application-models/ability-startup-with-explicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-explicit-want.md @@ -1,4 +1,7 @@ # Using Explicit Want to Start an Ability +When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. -When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, the explicit Want is used. For details about how to use the explicit Want, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). +## Using Explicit Want + +The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index 6550e5c628c642cf227cfde5f74eef7b61c8a52b..231610ad52a5ff53ce75b96277a18e4430c65d87 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -1,77 +1,80 @@ # Using Implicit Want to Open a Website - -## Prerequisites - -One or more browsers are installed on your device. - -The **module.json5** of a browser application is as follows: +This section uses the operation of using a browser to open a website as an example. It is assumed that one or more browser applications are installed on the device. To ensure that the browser application can work properly, configure the [module.json5 file](../quick-start/module-configuration-file.md) as follows: ```json -"skills": [ - { - "entities": [ - "entity.system.browsable" - // ... - ], - "actions": [ - "ohos.want.action.viewData" - // ... - ], - "uris": [ - { - "scheme": "https", - "host": "www.test.com", - "port": "8080", - // Prefix matching is used. - "pathStartWith": "query", - "type": "text/*" - }, +{ + "module": { + // ... + "abilities": [ { - "scheme": "http", // ... + "skills": [ + { + "entities": [ + "entity.system.home", + "entity.system.browsable" + // ... + ], + "actions": [ + "action.system.home", + "ohos.want.action.viewData" + // ... + ], + "uris": [ + { + "scheme": "https", + "host": "www.test.com", + "port": "8080", + // Prefix matching is used. + "pathStartWith": "query", + "type": "text/*" + }, + { + "scheme": "http", + // ... + } + // ... + ] + } + ] } - // ... ] - }, -] + } +} ``` +In the initiator UIAbility, use implicit Want to start the browser application. -## How to Develop +```ts +import common from '@ohos.app.ability.common'; -1. Use the custom function **implicitStartAbility** to start an ability. - - ```ts - async implicitStartAbility() { - try { - let want = { - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: "com.example.myapplication", - "action": "ohos.want.action.viewData", - // entities can be omitted. - "entities": [ "entity.system.browsable" ], - "uri": "https://www.test.com:8080/query/student", - "type": "text/plain" - } - let context = getContext(this) as common.UIAbilityContext; - await context.startAbility(want) - console.info(`explicit start ability succeed`) - } catch (error) { - console.info(`explicit start ability failed with ${error.code}`) - } - } - ``` - - The matching process is as follows: - 1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills**, the matching is successful. - - 2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills**, the matching is successful. +function implicitStartAbility() { + let context = getContext(this) as common.UIAbilityContext; + let wantInfo = { + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: "com.example.myapplication", + "action": "ohos.want.action.viewData", + // entities can be omitted. + "entities": ["entity.system.browsable"], + "uri": "https://www.test.com:8080/query/student", + "type": "text/plain" + } + context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) +} +``` - 3. If **uri** in the passed **want** parameter is included in **uris** under **skills**, which is concatenated into `https://www.test.com:8080/query*` (where \* is a wildcard), the matching is successful. +The matching process is as follows: - 4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful. +1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful. +2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful. +3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. +4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful. -2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. +When there are multiple matching applications, a dialog box is displayed for you to select one of them. The following figure shows an example. - ![stage-want1](figures/stage-want1.png) +![](figures/ability-startup-with-implicit-want1.png) \ No newline at end of file diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index 4e0a273f850b4919d0964580ebed89c053c273f7..9a4e71d3fa696ee6f2707545b80456df34fe85ac 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -29,6 +29,18 @@ AbilityStage is not automatically generated in the default project of DevEco Stu } } ``` + +4. Set **srcEntry** in the [module.json5 file](../quick-start/module-configuration-file.md) to the code path of the module. + ```json + { + "module": { + "name": "entry", + "type": "entry", + "srcEntry": "./ets/myabilitystage/MyAbilityStage.ts", + // ... + } + } + ``` [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) has the lifecycle callback [onCreate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageoncreate) and the event callbacks [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant), [onConfigurationUpdated()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate), and [onMemoryLevel()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonmemorylevel). @@ -41,6 +53,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu - **onConfigurationUpdated()** event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) class before project configuration. - **onMemoryLevel()** event callback: triggered when the system adjusts the memory. + When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the **onMemoryLevel()** lifecycle callback of AbilityStage to release unnecessary resources. @@ -54,4 +67,3 @@ When an application is switched to the background, it is cached in the backgroun } } ``` - diff --git a/en/application-dev/application-models/common-event-overview.md b/en/application-dev/application-models/common-event-overview.md index 0d3788b41b516d0af9619d320ceeefc3f52c74c5..d54fcf4786f0e22077cda0e6aae2d211bb2d0e90 100644 --- a/en/application-dev/application-models/common-event-overview.md +++ b/en/application-dev/application-models/common-event-overview.md @@ -15,11 +15,11 @@ Common events are classified into system common events and custom common events. Common events are also classified into unordered, ordered, and sticky common events. -- Unordered common events: CES forwards common events based on the subscription sequence, regardless of whether subscribers receive the events. +- Unordered common events: common events that CES forwards based on the subscription sequence, regardless of whether subscribers receive the events. -- Ordered common event: CES forwards common events to the next subscriber only after receiving a reply from the previous subscriber. +- Ordered common events: common events that CES forwards based on the subscriber priority. CES forwards common events to the subscriber with lower priority only after receiving a reply from the previous subscriber with higher priority. -- Sticky common event: a public event that can be sent to a subscriber before they initiate a subscription. Only system applications or system services can send sticky common event, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). +- Sticky common events: common events that can be sent to a subscriber before they initiate a subscription. Only system applications and system services can send sticky common events, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. diff --git a/en/application-dev/application-models/common-event-static-subscription.md b/en/application-dev/application-models/common-event-static-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..85852f5712df84107c6593160d276ed33557baf9 --- /dev/null +++ b/en/application-dev/application-models/common-event-static-subscription.md @@ -0,0 +1,105 @@ +# Subscribing to Common Events in Static Mode (for System Applications Only) + +## When to Use + +A static subscriber is started once it receives a target event published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. Note that this subscribing mode has negative impact on system power consumption. Therefore, exercise caution when using this mode. + +## How to Develop + +1. Declaring a Static Subscriber + + To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows: + + ```ts + import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' + + export default class StaticSubscriber extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event:' + event.event); + } + } + ``` + + You can implement service logic in the **onReceiveEvent** callback. + + + +2. Project Configuration for a Static Subscriber + + After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows: + + ```ts + { + "module": { + ...... + "extensionAbilities": [ + { + "name": "StaticSubscriber", + "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", + "description": "$string:StaticSubscriber_desc", + "icon": "$media:icon", + "label": "$string:StaticSubscriber_label", + "type": "staticSubscriber", + "visible": true, + "metadata": [ + { + "name": "ohos.extension.staticSubscriber", + "resource": "$profile:subscribe" + } + ] + } + ] + ...... + } + } + ``` + + Pay attention to the following fields in the JSON file: + + - **srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. + + - **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**. + + - **metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. + - **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. + - **resource**: path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**. + + A level-2 configuration file pointed to by **metadata** must be in the following format: + + ```ts + { + "commonEvents": [ + { + "name": "xxx", + "permission": "xxx", + "events":[ + "xxx" + ] + } + ] + } + ``` + + If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: + + - **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. + + - **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. + + - **events**: list of target events to subscribe to. + +3. Device System Configuration + + In the device system configuration file **/system/etc/app/install_list_capability.json**, add the bundle name of the static subscriber. + + ```json + { + "install_list": [ + { + "bundleName": "ohos.extension.staticSubscriber", + "allowCommonEvent": ["usual.event.A", "usual.event.B"], + } + ] + } + ``` + diff --git a/en/application-dev/application-models/common-event-subscription-overview.md b/en/application-dev/application-models/common-event-subscription-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..20064af92d3df2e6f7ab7d62c4f71f911848057a --- /dev/null +++ b/en/application-dev/application-models/common-event-subscription-overview.md @@ -0,0 +1,7 @@ +# Common Event Subscription Overview + +​The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not. + +- In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md). + +- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from StaticSubscriberExtensionAbility. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md). diff --git a/en/application-dev/application-models/common-event-subscription.md b/en/application-dev/application-models/common-event-subscription.md index ce61e40458a7cbd5c9ec226138535da93d3766b1..6cdc52ef9b798e48a911892f965db8fbf2aaa67f 100644 --- a/en/application-dev/application-models/common-event-subscription.md +++ b/en/application-dev/application-models/common-event-subscription.md @@ -1,9 +1,9 @@ -# Subscribing to Common Events +# Subscribing to Common Events in Dynamic Mode ## When to Use -You can create a subscriber object to subscribe to a common event so as to obtain the parameters passed in the event. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support). +In dynamic subscription mode, an application subscribes to a common event when it is running. If the subscribed event is published during the running period, the subscriber application will receive the event, together with the parameters passed in the event. For example, if an application expects to be notified of low battery so that it can reduce power consumption accordingly when running, then the application can subscribe to the low-battery event. Upon receiving the event, the application can close some unnecessary tasks to reduce power consumption. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support). ## Available APIs diff --git a/en/application-dev/application-models/common-event-unsubscription.md b/en/application-dev/application-models/common-event-unsubscription.md index c87017ef08c05e8a22097c4bd2a05f52fc758134..1a44675d61947325a8c1a8790ff5f53626e43f57 100644 --- a/en/application-dev/application-models/common-event-unsubscription.md +++ b/en/application-dev/application-models/common-event-unsubscription.md @@ -1,9 +1,9 @@ -# Unsubscribing from Common Events +# Unsubscribing from Common Events in Dynamic Mode ## When to Use -You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required. +You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required in dynamic mode. ## Available APIs @@ -21,12 +21,12 @@ You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#com import commonEventManager from '@ohos.commonEventManager'; ``` -2. Subscribe to an event by following the procedure described in [Subscribing to Common Events](common-event-subscription.md). +2. Subscribe to an event by following the procedure described in [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md). 3. Call **unsubscribe** in **CommonEvent** to unsubscribe from the common event. ```ts - // The subscriber object iscreated during event subscription. + // The subscriber object is created during event subscription. if (subscriber !== null) { commonEventManager.unsubscribe(subscriber, (err) => { if (err) { diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md index c04bea2916647804b51022cee1853f3b5d0a7d90..a057eb5c2b4796201cdd8bf35344ab600cfe0be0 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -1,111 +1,132 @@ # Using Want to Share Data Between Applications - Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications. +Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing. -## Prerequisites - -1. There are two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing through **startAbility()**, the application selector is started. The system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts that application to complete data sharing. - -2. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on the Want configuration used for data sharing. - -3. The following actions are involved in this section: - - **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector. - - **ACTION_SEND_DATA (ohos.want.action.sendData)**: action of launching the UI for sending a single data record. It is used to transfer data to the shared party. - - -## How to Develop - -- Sharing party - 1. In the stage mode, the [File Descriptor (FD)](../reference/apis/js-apis-fileio.md#fileioopensync) is used for file transfer. This example assumes that the path of the file to share is obtained. - - ```ts - import fileIO from '@ohos.fileio'; - - // let path = ... - // Open the file whose path is a variable. - let fileFd = fileIO.openSync(path, 0o102, 0o666); - ``` - - 2. As described in the prerequisites, the sharing party starts an application selector and shares the data to the selector, and the selector transfers the data to the shared party. Want of the sharing party must be nested at two layers. At the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. At the second layer, complete Want is declared in the custom field **parameters** to transfer the data to share. - - ```ts - import wantConstant from '@ohos.app.ability.wantConstant'; - - // let path = ... - // let fileFd = ... - // let fileSize = ... - let want = { - / This action is used to implicitly match the application selector. - action: wantConstant.Action.ACTION_SELECT, - // This is the custom parameter in the first layer of Want, - / which is intended to add information to the application selector. - parameters: { - // MIME type of PDF. - "ability.picker.type": "application/pdf", - "ability.picker.fileNames": [path], - "ability.picker.fileSizes": [fileSize], - // This nested Want ,which will be directly sent to the selected application. - "ability.want.params.INTENT": { - "action": "ohos.want.action.sendData", - "type": "application/pdf", - "parameters": { - "keyFd": {"type": "FD", "value": fileFd} - } - } - } +In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing. + +The following actions are involved for data sharing: + +- **ohos.want.action.select**: action of starting the application selector. +- **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party. + +## Sharing Party + +The sharing party starts an application selector and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. In the second layer, the data to share is declared + +in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application selector. The shared party obtains the shared data from **parameters**. + +```ts +import common from '@ohos.app.ability.common'; + +let fileType = 'application/pdf'; +let fileName = 'TestFile.pdf'; +let fileFd = -1; // Obtain the file descriptor (FD) of the file to share. +let fileSize; // Obtain the size of the file to share. + +function implicitStartAbility() { + let context = getContext(this) as common.UIAbilityContext; + let wantInfo = { + / This action is used to implicitly match the application selector. + action: 'ohos.want.action.select', + // This is the custom parameter in the first layer of Want, + / which is intended to add information to the application selector. + parameters: { + // MIME type of PDF. + "ability.picker.type": fileType, + "ability.picker.fileNames": [fileName], + "ability.picker.fileSizes": [fileSize], + // This is nested Want ,which will be directly sent to the selected application. + "ability.want.params.INTENT": { + "action": "ohos.want.action.sendData", + "type": "application/pdf", + "parameters": { + "keyFd": { "type": "FD", "value": fileFd } + } } - ``` - - In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: - - - **"ability.picker.type"**: The application selector renders the file type icon based on this field. - - **"ability.picker.fileNames"**: The application selector displays the file name based on this field. - - **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte. - - **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. - - For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows: - - ![stage-want2](figures/stage-want2.png) - - In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application. - -- Shared party - 1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows: - - ```ts - "skills": [ - { - "entities": [ + } + } + context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) +} +``` + +> **NOTE** +> +> Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md). + +In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application selector: + +- **ability.picker.type**: file type icon. +- **ability.picker.fileNames**: file name. +- **ability.picker.fileSizes**: file size, in bytes. +- **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping. + +The following figure shows an example. +![](figures/ability-startup-with-implicit-want2.png) + +## Shared Party + +To enable the shared party to identify the shared content, configure **skills** in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility of the shared party. The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT** of the sharing party, respectively. + +```json +{ + "module": { + // ... + "abilities": [ + { + // ... + "skills": [ + { // ... - ], - "actions": [ + "actions": [ + "action.system.home", "ohos.want.action.sendData" // ... - ], - "uris": [ - { - "type": "application/pdf" - }, - // ... - ] - }, - ] - ``` - - The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT**, respectively. - - Files can be transferred in FD mode, but not URI mode. In implicit matching, the **type** field in Want must match the **type** field in **uris** under **skills** of the shared party. Therefore, specify only the **type** field in **uris**. If **host** and **port** are specified, the matching fails. The application selector initiates implicit matching based on **ability.want.params.INTENT**. Therefore, when the **uri** field added to **ability.want.params.INTENT** matches the **uris** field under **skills**, the matching is successful and additional data can be transferred. - 2. After the application selector starts the shared party, the system calls **onCreate** and passes **ability.want.params.INTENT** to the **want** parameter. - - ```ts - onCreate(want, launchParam) { - // When keyFd is undefined, the application crashes. - if (want["parameters"]["keyFd"] !== undefined) { - // Receive the file descriptor. - let fd = want["parameters"]["keyFd"].value; - // ... - } + ], + "uris": [ + { + "type": "application/pdf" + }, + ] + } + ] } - ``` + ] + } +} +``` + +After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want. + +The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations. + +```json +{ + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry", + "uri": "", + "type": "application/pdf", + "flags": 0, + "action": "ohos.want.action.sendData", + "parameters": { + "component.startup.newRules": true, + "keyFd": { + "type": "FD", + "value": 36 + }, + "mime-type": "application/pdf", + "moduleName": "entry", + "ohos.aafwk.param.callerPid": 3488, + "ohos.aafwk.param.callerToken": 537379209, + "ohos.aafwk.param.callerUid": 20010014 + }, + "entities": [] +} +``` diff --git a/en/application-dev/application-models/datashareextensionability.md b/en/application-dev/application-models/datashareextensionability.md index 5b07ba68180fbcc2a51047d37ca9a82addd89cd8..f671848f890277af92fc23869c5db0d57b02a316 100644 --- a/en/application-dev/application-models/datashareextensionability.md +++ b/en/application-dev/application-models/datashareextensionability.md @@ -1,4 +1,4 @@ -# DataShareExtensionAbility +# DataShareExtensionAbility (for System Applications Only) -DataShareExtensionAbility is available only for system application. It provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md). +DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md). diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md index 8b3197383e17810cfee7c044611cf2286f4a987d..809e4e8f70ed31ad361e18dd8cb7e079ddf93086 100644 --- a/en/application-dev/application-models/extensionability-overview.md +++ b/en/application-dev/application-models/extensionability-overview.md @@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. -- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. +- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. @@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab - [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast. -- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows system applications to display UIs of other applications. +- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png new file mode 100644 index 0000000000000000000000000000000000000000..3f871f4816dfcf60a5c30e39b6d0ead2f8eb711e Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png differ diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png new file mode 100644 index 0000000000000000000000000000000000000000..4f1656a3c20e472e260e8e125c42b47c11a35abb Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png differ diff --git a/en/application-dev/application-models/figures/mission-chain3.png b/en/application-dev/application-models/figures/mission-chain3.png index e02c135ad4a90f99bb65bdccd821d29990b9536e..0357874ea633a490da800ef5baa2e70d53ce6a2d 100644 Binary files a/en/application-dev/application-models/figures/mission-chain3.png and b/en/application-dev/application-models/figures/mission-chain3.png differ diff --git a/en/application-dev/application-models/figures/mission-list-recent.png b/en/application-dev/application-models/figures/mission-list-recent.png new file mode 100644 index 0000000000000000000000000000000000000000..bfc35532ad4907fd3a1bfcb61110ed393ea19d1c Binary files /dev/null and b/en/application-dev/application-models/figures/mission-list-recent.png differ diff --git a/en/application-dev/application-models/figures/mission-set-task-snapshot-icon.png b/en/application-dev/application-models/figures/mission-set-task-snapshot-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..9d1ba2503f4e1a5d3b2aafdd93923c3f6c411998 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-set-task-snapshot-icon.png differ diff --git a/en/application-dev/application-models/figures/mission-set-task-snapshot-label.png b/en/application-dev/application-models/figures/mission-set-task-snapshot-label.png new file mode 100644 index 0000000000000000000000000000000000000000..c8348685cc0fd521186aa10e8d04495422fc0206 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-set-task-snapshot-label.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png deleted file mode 100644 index 558f0a8588d7785eaad1402e68d6ba60c3118f27..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want1.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/stage-want2.png b/en/application-dev/application-models/figures/stage-want2.png deleted file mode 100644 index 72829adade52ee11419d726f19e218ec4de15220..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want2.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/start-uiability-floating-window.png b/en/application-dev/application-models/figures/start-uiability-floating-window.png new file mode 100644 index 0000000000000000000000000000000000000000..8626c3704f3e60c8efb3d6b6ea0468a7c2958a4f Binary files /dev/null and b/en/application-dev/application-models/figures/start-uiability-floating-window.png differ diff --git a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png index 92292f2c6ef4c9cbd06da2a523f27b571a957e2b..344cf05e96c539ca73fdb9282625a1d1cb8584e7 100644 Binary files a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png and b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index 6d30435a819da49855cf9ae818bac419a1c0b614..d90a10995f0aeba773179fc7807ab25711b4594c 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -1,9 +1,9 @@ -# Cross-Device Migration +# Cross-Device Migration (for System Applications Only)] ## When to Use -Cross-device migration is available only for system applications. The main task is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities: +The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities: - Storage and restoration of custom data diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index fe22c3b33db46b5a353295582a5cc6a27f690d20..f5d82af32da86796d81dc1bebed1d6ff804f2532 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -1,9 +1,9 @@ -# Multi-device Collaboration +# Multi-device Collaboration (for System Applications Only) ## When to Use -Multi-device coordination is available only for system applications. It involves the following scenarios: +Multi-device coordination involves the following scenarios: - [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned) @@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn ## Using Cross-Device Ability Call -The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction). +The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only). The following describes how to implement multi-device collaboration through cross-device ability call. @@ -319,10 +319,10 @@ The following describes how to implement multi-device collaboration through cros | startAbilityByCall(want: Want): Promise<Caller>; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | off(method: string): void | Callback invoked when the callee ability deregisters a method.| -| call(method: string, data: rpc.Sequenceable): Promise<void> | Sends agreed sequenceable data to the callee ability.| -| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| +| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the callee ability.| +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence>| Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | release(): void | Releases the caller object.| -| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| +| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| ### How to Develop @@ -348,16 +348,15 @@ The following describes how to implement multi-device collaboration through cros For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. 1. Configure the launch type of the UIAbility. + Set **launchType** of the callee ability to **singleton** in the **module.json5** file. - Set **launchType** of the callee ability to **singleton** in the **module.json5** file. + | JSON Field| Description| + | -------- | -------- | + | "launchType"| Ability launch type. Set this parameter to **singleton**.| - | JSON Field| Description| - | -------- | -------- | - | "launchType"| Ability launch type. Set this parameter to **singleton**.| + An example of the UIAbility configuration is as follows: - An example of the UIAbility configuration is as follows: - - + ```json "abilities":[{ "name": ".CalleeAbility", @@ -369,19 +368,18 @@ The following describes how to implement multi-device collaboration through cros "visible": true }] ``` - 2. Import the **UIAbility** module. ```ts import Ability from '@ohos.app.ability.UIAbility'; ``` - - 3. Define the agreed sequenceable data. - - The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. - + 3. Define the agreed parcelable data. + + The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. + + ```ts - export default class MySequenceable { + export default class MyParcelable { num: number = 0; str: string = ""; @@ -390,71 +388,69 @@ The following describes how to implement multi-device collaboration through cros this.str = string; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } ``` - 4. Implement **Callee.on** and **Callee.off**. - - In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. - - ```ts - const TAG: string = '[CalleeAbility]'; - const MSG_SEND_METHOD: string = 'CallSendMsg'; - - function sendMsgCallback(data) { - console.info('CalleeSortFunc called'); - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); - } - - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback); - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); - } - } + + In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); - } - } - } - ``` - + ```ts + const TAG: string = '[CalleeAbility]'; + const MSG_SEND_METHOD: string = 'CallSendMsg'; + + function sendMsgCallback(data) { + console.info('CalleeSortFunc called'); + + // Obtain the parcelable data sent by the caller ability. + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + + // Process the data. + // Return the parcelable data result to the caller ability. + return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); + } + + export default class CalleeAbility extends Ability { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback); + } catch (error) { + console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); + } + } + + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD); + } catch (error) { + console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); + } + } + } + ``` + 4. Obtain the caller object and access the callee ability. 1. Import the **UIAbility** module. ```ts import Ability from '@ohos.app.ability.UIAbility'; ``` - 2. Obtain the caller object. - + The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. - + ```ts async onButtonGetRemoteCaller() { @@ -483,14 +479,14 @@ The following describes how to implement multi-device collaboration through cros For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). -5. Sends agreed sequenceable data to the callee ability. - 1. The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. +5. Sends agreed parcelable data to the callee ability. + 1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. ```ts const MSG_SEND_METHOD: string = 'CallSendMsg'; async onButtonCall() { try { - let msg = new MySequenceable(1, 'origin_Msg'); + let msg = new MyParcelable(1, 'origin_Msg'); await this.caller.call(MSG_SEND_METHOD, msg); } catch (error) { console.info(`caller call failed with ${error}`); @@ -505,12 +501,12 @@ The following describes how to implement multi-device collaboration through cros backMsg: string = ''; async onButtonCallWithResult(originMsg, backMsg) { try { - let msg = new MySequenceable(1, originMsg); + let msg = new MyParcelable(1, originMsg); const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg); console.info('caller callWithResult succeed'); - let result = new MySequenceable(0, ''); - data.readSequenceable(result); + let result = new MyParcelable(0, ''); + data.readParcelable(result); backMsg(result.str); console.info(`caller result is [${result.num}, ${result.str}]`); } catch (error) { @@ -521,8 +517,8 @@ The following describes how to implement multi-device collaboration through cros 6. Release the caller object. - When the caller object is no longer required, use **release()** to release it. - + When the caller object is no longer required, use **release()** to release it. + ```ts releaseCall() { try { diff --git a/en/application-dev/application-models/inputmethodextentionability.md b/en/application-dev/application-models/inputmethodextentionability.md new file mode 100644 index 0000000000000000000000000000000000000000..9a025339cab6a5f555fd61b15597400b31affeb7 --- /dev/null +++ b/en/application-dev/application-models/inputmethodextentionability.md @@ -0,0 +1,366 @@ +# InputMethodExtensionAbility Development + +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) is an ExtensionAbility component of the inputMethod type that provides extension capabilities for the input method framework. + +InputMethodExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller. + + +InputMethodExtensionAbility provides related capabilities through the [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md). + + +## Implementing an Input Method Application + +InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required. + +- **onCreate** + + This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. + + > **NOTE** + > + > If a service has been created, starting it again does not trigger the **onCreate()** callback. + +- **onDestroy** + + This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. + + +## How to Develop + +To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows: + +In the **ets** directory of the target module, right-click and choose **New** > **Extention Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility. + +> **NOTE** +> +> When compiling the input method application, use the signature at the system_core level. Otherwise, the application will not be able to start the keyboard. + +The minimum template implements an input method application with the most basic features, such as starting the keyboard, entering text, and deleting input. You can diversify the feature set of the application by, for example, adding the feature to hide the keyboard. + +The minimum template contains four files: **KeyboardController.ts**, **InputMethodService.ts**, **Index.ets**, and **KeyboardKeyData.ts**. The file directory is as follows: + +``` +/src/main/ +├── ets/inputmethodextability +│ └──model/KeyboardController.ts # Shows the keyboard. +│ └──InputMethodService.ts # Customizes a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks. +│ └──pages +│ └── Index.ets # Draws the keyboard and adds the input and deletion features. +│ └── KeyboardKeyData.ts # Defines keyboard attributes. +├── resources/base/profile/main_pages.json +``` + +## File Introduction + +1. **InputMethodService.ts** file: + + In this file, add the dependency package for importing InputMethodExtensionAbility. Customize a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks. + + ```ts + import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility'; + import { KeyboardController } from './model/KeyboardController' + + export default class InputDemoService extends InputMethodExtensionAbility { + private keyboardController: KeyboardController; + + onCreate(want) { + this.keyboardController = new KeyboardController(this.context); + this.keyboardController.onCreate(); // Initialize the window and register an event listener for the input method framework. + } + + onDestroy() { + console.log("onDestroy."); + this.context.destroy(); + } + } + ``` + +2. **KeyboardController.ts** file: + + ```ts + import inputMethodEngine from '@ohos.inputMethodEngine'; + import display from '@ohos.display'; + import windowManager from '@ohos.window'; + + // Call the getInputMethodAbility API to obtain an instance, and then call the other APIs of the input method framework based on the instance. + globalThis.inputAbility = inputMethodEngine.getInputMethodAbility(); + + export class KeyboardController { + mContext; // Save the context attribute in InputMethodExtensionAbility. + WINDOW_TYPE_INPUT_METHOD_FLOAT = 2105; // Define the window type. The value 2105 indicates the input method window type, which is used to create an input method application window. + windowName = 'inputApp'; + private windowHeight: number = 0; + private windowWidth: number = 0; + private nonBarPosition: number = 0; + private isWindowShowing: boolean = false; + + constructor(context) { + this.mContext = context; + } + + public onCreate(): void + { + this.initWindow(); // Initialize the window. + this.registerListener(); // Register an event listener for the input method framework. + } + + public onDestroy(): void // Destroy the instance. + { + this.unRegisterListener(); // Deregister the event listener. + let win = windowManager.findWindow(this.windowName); + win.destroyWindow(); // Destroy the window. + this.mContext.terminateSelf(); // Terminate the InputMethodExtensionAbility service. + } + + private initWindow(): void // Initialize the window. + { + let dis = display.getDefaultDisplaySync(); + let dWidth = dis.width; + let dHeight = dis.height; + let keyHeightRate = 0.47; + let keyHeight = dHeight * keyHeightRate; + this.windowWidth = dWidth; + this.windowHeight = keyHeight; + this.nonBarPosition = dHeight - keyHeight; + + let config = { + name: this.windowName, + windowType: this.WINDOW_TYPE_INPUT_METHOD_FLOAT, + ctx: this.mContext + } + windowManager.createWindow(config).then((win) => { // Create a window of the specified type. + win.resize(dWidth, keyHeight).then(() => { + win.moveWindowTo(0, this.nonBarPosition).then(() => { + win.setUIContent('pages/InputMethodExtAbility/Index').then(() => { + }); + }); + }); + }); + } + + private registerListener(): void + { + this.registerInputListener(); // Register an event listener for the input method framework service. + globalThis.inputAbility.on('keyboardShow', () => {// Register an event listener for the keyboard . + if (this.isWindowShowing) { + return; + } + this.isWindowShowing = true; + this.showHighWindow(); // Show the window. + }); + ... + // Register a listener for keyboard hiding. + } + + private registerInputListener() { // Register a listener for the enabling and disabling events of the input method framework service. + globalThis.inputAbility.on('inputStart', (kbController, textInputClient) => { + globalThis.textInputClient = textInputClient; // This is an input method client instance, based on which you can call the functional APIs that the input method framework provides for the input method application. + globalThis.keyboardController = kbController; + }) + globalThis.inputAbility.on('inputStop', (imeId) => { + if (imeId == "Bundle name/Ability name") { + this.onDestroy(); + } + }); + } + + private unRegisterListener(): void + { + globalThis.inputAbility.off('inputStart'); + globalThis.inputAbility.off('inputStop', () => {}); + globalThis.inputAbility.off('keyboardShow'); + } + + private showHighWindow() { + let win = windowManager.findWindow(this.windowName) + win.resize(this.windowWidth, this.windowHeight).then(() => { + win.moveWindowTo(0, this.nonBarPosition).then(() => { + win.showWindow().then(() => { + this.isWindowShowing = false; + }) + }) + }) + } + } + ``` + +3. **KeyboardKeyData.ts** file: + + In this file you can define the content displayed on the soft keyboard. + + ```ts + export interface sourceListType { + content: string, + } + + export let numberSourceListData: sourceListType[] = [ + { + content: '1' + }, + { + content: '2' + }, + { + content: '3' + }, + { + content: '4' + }, + { + content: '5' + }, + { + content: '6' + }, + { + content: '7' + }, + { + content: '8' + }, + { + content: '9' + }, + { + content: '0' + } + ] + ``` + +4. **Index.ets** file: + + This file describes the functions of keys. For example, the number keys print numbers in the text box, and the delete key deletes what's entered. + + Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file. + + ```ets + import { numberSourceListData, sourceListType } from './keyboardKeyData' + + @Component + struct keyItem { + private keyValue: sourceListType + @State keyBgc: string = "#fff" + @State keyFontColor: string = "#000" + + build() { + Column() { + Flex({ direction: FlexDirection.Column, + alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.keyValue.content).fontSize(20).fontColor(this.keyFontColor) + } + } + .backgroundColor(this.keyBgc) + .borderRadius(6) + .width("8%") + .height("65%") + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { + globalThis.textInputClient.insertText(this.keyValue.content); + } + }) + } + } + + // Component used for deletion. + @Component + export struct deleteItem { + @State keyBgc: string = "#fff" + @State keyFontColor: string = "#000" + + build() { + Column() { + Flex({ direction: FlexDirection.Column, + alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text("Delete").fontSize(20).fontColor(this.keyFontColor) + } + } + .backgroundColor(this.keyBgc) + .width("13%") + .borderRadius(6) + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { + globalThis.textInputClient.deleteForward(1); + } + }) + } + } + + // Numeric keyboard + @Component + struct numberMenu { + private numberList: sourceListType[] + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) { + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + ForEach(this.numberList, (item: sourceListType) => { // First row on the numeric keyboard + keyItem({ keyValue: item }) + }, (item: sourceListType) => item.content); + } + .padding({ top: "2%" }) + .width("96%") + .height("25%") + + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + deleteItem() + } + .width("96%") + .height("25%") + } + } + } + + @Entry + @Component + struct Index { + private numberList: sourceListType[] = numberSourceListData + + build() { + Stack() { + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.End + }) { + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.SpaceBetween + }) { + numberMenu({ + numberList: this.numberList + }) + } + .align(Alignment.End) + .width("100%") + .height("75%") + } + .height("100%").align(Alignment.End).backgroundColor("#cdd0d7") + } + .position({ x: 0, y: 0 }).zIndex(99999) + } + } + ``` + + Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntrance** to the code path of the InputMethodExtensionAbility component. + + ```ts + { + "module": { + // ... + "extensionAbilities": [ + { + "description": "inputMethod", + "icon": "$media:icon", + "name": "InputMethodExtAbility", + "srcEntrance": "./ets/inputmethodextability/InputMethodService.ts", + "type": "inputMethod", + "visible": true, + } + ] + } + } + ``` + + + diff --git a/en/application-dev/application-models/itc-with-worker.md b/en/application-dev/application-models/itc-with-worker.md index 8cbe53eeea067ae1875a8ff4b73bc4cde7bdd629..996ab941b0244571dff6116a45ab5e2165cf1184 100644 --- a/en/application-dev/application-models/itc-with-worker.md +++ b/en/application-dev/application-models/itc-with-worker.md @@ -18,7 +18,7 @@ To develop the Worker mode, perform the following steps: } ``` -2. Create the **worker.js** file based on the configuration in **build-profile.json5**. +2. Create the **worker.ts** file based on the configuration in **build-profile.json5**. ```ts import worker from '@ohos.worker'; @@ -58,7 +58,7 @@ To develop the Worker mode, perform the following steps: ```ts import worker from '@ohos.worker'; - let wk = new worker.ThreadWorker("../workers/worker.js"); + let wk = new worker.ThreadWorker("../workers/worker.ts"); // Send a message to the worker thread. wk.postMessage("message from main thread.") @@ -74,6 +74,6 @@ To develop the Worker mode, perform the following steps: > **NOTE** > -> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.js** when creating a worker thread in the FA model. +> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model. > > - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). diff --git a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md new file mode 100644 index 0000000000000000000000000000000000000000..9fdc03477c0552f523a0ee9c40c6fa5b8d7c4363 --- /dev/null +++ b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md @@ -0,0 +1,51 @@ +# Setting the Icon and Name of a Mission Snapshot + +Setting a unique icon and name for each mission snapshot of an application helps you better manage the missions and functions of the application. + +By default, the **icon** and **label** fields in the [abilities tag](../quick-start/module-configuration-file.md#abilities) of the [module.json5 file](../quick-start/module-configuration-file.md) are used to set the icon and label. + +Figure 1 Mission snapshot of a UIAbility + +![](figures/mission-list-recent.png) + +You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) and [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to customize the icon and name for a mission snapshot. For example, for a UIAbility instance with the launch type set to **standard**, you can configure the icon and name for each mission snapshot based on different functions. + +This document describes the following operations: + +- [Setting a Mission Snapshot Icon (for System Applications Only)](#setting-a-mission-snapshot-icon-for-system-applications-only) +- [Setting a Mission Snapshot Name](#setting-a-mission-snapshot-name) + +## Setting a Mission Snapshot Icon (for System Applications Only) + +Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +```ts +let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. + +this.context.setMissionIcon(imagePixelMap, (err) => { + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); +}) +``` + +The display effect is shown below. + +Figure 2 Mission snapshot icon + +![](figures/mission-set-task-snapshot-icon.png) + +## Setting a Mission Snapshot Name + +Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot. + +```ts +this.context.setMissionLabel('test').then(() => { + console.info('setMissionLabel succeeded.'); +}).catch((err) => { + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +The display effect is shown below. + +Figure 3 Mission snapshot name + +![](figures/mission-set-task-snapshot-label.png) \ No newline at end of file diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index d64d884b1e3021193f63445913886830218df6e1..9ff7a0ae5d6df7574da19565c81411236dba3dda 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ This topic describes how to use ServiceExtensionAbility in the following scenarios: -- [Implementing a Background Service](#implementing-a-background-service) +- [Implementing a Background Service (for System Applications Only)](#implementing-a-background-service-for-system-applications-only) -- [Starting a Background Service](#starting-a-background-service) +- [Starting a Background Service (for System Applications Only)](#starting-a-background-service-for-system-applications-only) - [Connecting to a Background Service](#connecting-to-a-background-service) @@ -33,9 +33,9 @@ This topic describes how to use ServiceExtensionAbility in the following scenari > - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. -## Implementing a Background Service +## Implementing a Background Service (for System Applications Only) -This feature applies only to system applications. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. +[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. **Figure 1** ServiceExtensionAbility lifecycle ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) @@ -164,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com ``` -## Starting a Background Service +## Starting a Background Service (for System Applications Only) -This feature applies only to system applications. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. +A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. > **NOTE** > diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 4e998a15d23d298bfdb402bd18ea0db2a9f819eb..36ee305b49698c1f6e6cf216174f77212f1d53e4 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -1,7 +1,7 @@ -# Starting a Remote PageAbility +# Starting a Remote PageAbility (for System Applications Only) -This feature applies only to system applications. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility. +The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility. In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility. diff --git a/en/application-dev/application-models/static-subscriber-extension-ability.md b/en/application-dev/application-models/static-subscriber-extension-ability.md deleted file mode 100644 index ae6d9a80b7ab6c693d06e7bfe8bfb11b4db94ab8..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/static-subscriber-extension-ability.md +++ /dev/null @@ -1,107 +0,0 @@ -# StaticSubscriberExtensionAbility Development - -## Scenario Description - -​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.** - - - -## How to Develop - -1. Prerequisites - - The application must meet the following requirements: - - The application is a system application. - - The application is developed using the full SDK. - - The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**. - - - -2. Declaring a Static Subscriber - - To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows: - - ```ts - import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' - - export default class StaticSubscriber extends StaticSubscriberExtensionAbility { - onReceiveEvent(event) { - console.log('onReceiveEvent, event:' + event.event); - } - } - ``` - - You can implement service logic in the **onReceiveEvent** callback. - - - -3. Project Configuration for a Static Subscriber - - After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows: - - ```ts - { - "module": { - ...... - "extensionAbilities": [ - { - "name": "StaticSubscriber", - "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", - "description": "$string:StaticSubscriber_desc", - "icon": "$media:icon", - "label": "$string:StaticSubscriber_label", - "type": "staticSubscriber", - "visible": true, - "metadata": [ - { - "name": "ohos.extension.staticSubscriber", - "resource": "$profile:subscribe" - } - ] - } - ] - ...... - } - } - ``` - - Pay attention to the following fields in the JSON file: - - **srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. - - **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**. - - **metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**. - - A level-2 configuration file pointed to by **metadata** must be in the following format: - - ```ts - { - "commonEvents": [ - { - "name": "xxx", - "permission": "xxx", - "events":[ - "xxx" - ] - } - ] - } - ``` - - If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: - - **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. - - **permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. - - **events**: list of subscribed target events - - - -## Samples - -For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber). diff --git a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md new file mode 100644 index 0000000000000000000000000000000000000000..c231f483e9bcd8f83faf49d40007730d0f854de5 --- /dev/null +++ b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md @@ -0,0 +1,172 @@ +# Subscribing to System Environment Variable Changes + +System environment variables are system settings (for example, the system language or screen direction) of a device that may change during the running of an application. + +By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size. + +The system environment variable changes are usually triggered by options in **Settings** or icons in **Control Panel**. For details about the system environment variables that support subscription, see [Configuration](../reference/apis/js-apis-app-ability-configuration.md). + +In OpenHarmony, you can subscribe to system environment variable changes in the following ways: + +- [Using ApplicationContext for Subscription](#using-applicationcontext-for-subscription) +- [Using AbilityStage for Subscription](#using-abilitystage-for-subscription) +- [Using UIAbility for Subscription](#using-uiability-for-subscription) +- [Using ExtensionAbility for Subscription](#using-extensionability-for-subscription) + +## Using ApplicationContext for Subscription + +[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides an API for registering a callback function to subscribe to the system environment variable changes. It also provides an API for deregistration so you can release related resources when they are no longer needed. + +1. Call **ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)** to subscribe to changes in system environment variables. The code snippet below is used to subscribe to system language changes on a page. + + ```ts + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + private context = getContext(this) as common.UIAbilityContext; + private callbackId: number; // ID of the subscription for system environment variable changes. + + subscribeConfigurationUpdate() { + let systemLanguage: string = this.context.config.language; // Obtain the system language in use. + + // 1. Obtain an ApplicationContext object. + let applicationContext = this.context.getApplicationContext(); + + // 2. Subscribe to system environment variable changes through ApplicationContext. + let environmentCallback = { + onConfigurationUpdated(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + + if (this.systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. + } + }, + onMemoryLevel(level) { + console.info(`onMemoryLevel level: ${level}`); + } + } + + this.callbackId = applicationContext.on('environment', environmentCallback); + } + + // Page display. + build() { + // ... + } + } + ``` + +2. Call **ApplicationContext.off(type: 'environment', callbackId: number)** to release the resources. + + ```ts + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + private context = getContext(this) as common.UIAbilityContext; + private callbackId: number; // ID of the subscription for system environment variable changes. + + unsubscribeConfigurationUpdate() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.off('environment', this.callbackId); + } + + // Page display. + build() { + // ... + } + } + ``` + +## Using AbilityStage for Subscription + +The AbilityStage component provides the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object. + +> **NOTE** +> +> - AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). +> - The callback used to subscribe to system environment variable changes has the same lifecycle as the [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) instance and will be destroyed when the instance is destroyed. + +The code snippet below uses the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback to subscribe to the system language changes. + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +let systemLanguage: string; // System language in use. + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } + + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. + } + } +} +``` + +## Using UIAbility for Subscription + +The UIAbility component provides the **UIAbility.onConfigurationUpdate()** callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object, without restarting the UIAbility. + +> **NOTE** +> +> The callback used to subscribe to system environment variable changes has the same lifecycle as the UIAbility instance and will be destroyed when the instance is destroyed. + +The code snippet below uses the **onConfigurationUpdate()** callback to subscribe to the system language changes. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +let systemLanguage: string; // System language in use. + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } + + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. + } + } + + // ... +} +``` + +## Using ExtensionAbility for Subscription + +The ExtensionAbility component provides the **onConfigurationUpdate()** callback for subscribing system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object. + +> **NOTE** +> +> The callback used to subscribe to system environment variable changes has the same lifecycle as the ExtensionAbility instance and will be destroyed when the instance is destroyed. + +The code snippet below uses FormExtensionAbility as an example to describe how to use the **onConfigurationUpdate()** callback to subscribe to system environment variable changes. + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class EntryFormAbility extends FormExtensionAbility { + onConfigurationUpdate(newConfig) { + console.info(`newConfig is ${JSON.stringify(newConfig)}`); + } + + // ... +} +``` diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index ac3c18e36de67e66e496a92da2269c063503ce7e..25f509e9032a3670664937307fe4691b6a09bc28 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -15,9 +15,11 @@ This topic describes the UIAbility interaction modes in the following scenarios. - [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) +- [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only) + - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) -- [Using Ability Call to Implement UIAbility Interaction](#using-ability-call-to-implement-uiability-interaction) +- [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only) ## Starting UIAbility in the Same Application @@ -202,8 +204,7 @@ This section describes how to start the UIAbility of another application through ``` The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. - - ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) + ![](figures/uiability-intra-device-interaction.png) 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). @@ -307,6 +308,55 @@ If you want to obtain the return result when using implicit Want to start the UI }) ``` +## Starting UIAbility with Window Mode Specified (for System Applications Only) + +By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen. + +In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI. + +In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time. + +In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency. + +The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). + +> **NOTE** +> +> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. +> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities tag](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. + +The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page. + +1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). +2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window. + +For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). + +```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + +let wantInfo = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, +} +let options = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING +} +// context is the ability-level context of the initiator UIAbility. +this.context.startAbility(wantInfo, options).then(() => { + // ... +}).catch((err) => { + // ... +}) +``` + +The display effect is shown below. +![](figures/start-uiability-floating-window.png) ## Starting a Specified Page of UIAbility @@ -422,9 +472,9 @@ In summary, when a UIAbility instance of application A has been created and the > When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. -## Using Ability Call to Implement UIAbility Interaction +## Using Ability Call to Implement UIAbility Interaction (for System Applications Only) -This feature applies only to system applications. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. +Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: @@ -449,9 +499,9 @@ Ability call is usually used in the following scenarios: The following figure shows the ability call process. -Figure 1 Ability call process + Figure 1 Ability call process -![call](figures/call.png) + ![call](figures/call.png) - The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. @@ -476,8 +526,8 @@ The following table describes the main APIs used for the ability call. For detai | startAbilityByCall(want: Want): Promise<Caller> | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | off(method: string): void | Callback invoked when the callee ability deregisters a method.| -| call(method: string, data: rpc.Sequenceable): Promise<void> | Sends agreed sequenceable data to the callee ability.| -| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| +| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the callee ability.| +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | release(): void | Releases the caller object.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| @@ -495,37 +545,39 @@ For the callee ability, implement the callback to receive data and the methods t 1. Configure the ability launch type. Set **launchType** of the callee ability to **singleton** in the **module.json5** file. - + | JSON Field| Description| | -------- | -------- | | "launchType" | Ability launch type. Set this parameter to **singleton**.| - + An example of the ability configuration is as follows: - - ```json - "abilities":[{ - "name": ".CalleeAbility", - "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "visible": true - }] - ``` - + + + ```json + "abilities":[{ + "name": ".CalleeAbility", + "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", + "launchType": "singleton", + "description": "$string:CalleeAbility_desc", + "icon": "$media:icon", + "label": "$string:CalleeAbility_label", + "visible": true + }] + ``` + 2. Import the **UIAbility** module. ```ts import Ability from '@ohos.app.ability.UIAbility'; ``` -3. Define the agreed sequenceable data. +3. Define the agreed parcelable data. The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. - + + ```ts - export default class MySequenceable { + export default class MyParcelable { num: number = 0 str: string = "" @@ -534,15 +586,15 @@ For the callee ability, implement the callback to receive data and the methods t this.str = string } - marshalling(messageParcel) { - messageParcel.writeInt(this.num) - messageParcel.writeString(this.str) + marshalling(messageSequence) { + messageSequence.writeInt(this.num) + messageSequence.writeString(this.str) return true } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt() - this.str = messageParcel.readString() + unmarshalling(messageSequence) { + this.num = messageSequence.readInt() + this.str = messageSequence.readString() return true } } @@ -550,8 +602,7 @@ For the callee ability, implement the callback to receive data and the methods t 4. Implement **Callee.on** and **Callee.off**. - The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: - + The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: ```ts const TAG: string = '[CalleeAbility]'; const MSG_SEND_METHOD: string = 'CallSendMsg'; @@ -559,14 +610,14 @@ For the callee ability, implement the callback to receive data and the methods t function sendMsgCallback(data) { console.info('CalleeSortFunc called'); - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); + // Obtain the parcelable data sent by the caller ability. + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); + // Return the parcelable data result to the caller ability. + return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); } export default class CalleeAbility extends Ability { @@ -588,7 +639,6 @@ For the callee ability, implement the callback to receive data and the methods t } ``` - ### Accessing the Callee Ability 1. Import the **UIAbility** module. @@ -598,9 +648,9 @@ For the callee ability, implement the callback to receive data and the methods t ``` 2. Obtain the caller interface. - - The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. + The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. + ```ts // Register the onRelease() listener of the caller ability. private regOnRelease(caller) { diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index 70c212ed46e769dbdf4e0c1fd347403c463f6004..5f2f21b1aff90a27e7307d82045941ec76b98475 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -17,13 +17,10 @@ The launch type of the UIAbility component refers to the state of the UIAbility Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. -**Figure 1** Demonstration effect in singleton mode +**Figure 1** Demonstration effect in singleton mode +![uiability-launch-type1](figures/uiability-launch-type1.png) -![uiability-launch-type1](figures/uiability-launch-type1.png) - -> **NOTE** -> -> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. +> **NOTE**
Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**. @@ -47,9 +44,8 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. -**Figure 2** Demonstration effect in standard mode - -![standard-mode](figures/standard-mode.png) +**Figure 2** Demonstration effect in standard mode +![standard-mode](figures/standard-mode.png) To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**. @@ -73,14 +69,13 @@ To use the standard mode, set **launchType** in the [module.json5 configuration The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. -**Figure 3** Demonstration effect in specified mode +**Figure 3** Demonstration effect in specified mode +![uiability-launch-type2](figures/uiability-launch-type2.png) -![uiability-launch-type2](figures/uiability-launch-type2.png) +For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. -For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility. +1. In SpecifiedAbility, set the **launchType** field in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**. -1. In SpecifiedAbility, set the **launchType** field in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **specified**. - ```json { "module": { @@ -95,9 +90,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of } ``` -2. Before a UIAbility instance is created, you can create a unique string key for the instance. The key is bound to the UIAbility instance when it is created. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application is asked which UIAbility instance is used to respond to the [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) request. - In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances. - +2. Create a unique string key for the instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance. + ```ts // Configure an independent key for each UIAbility instance. // For example, in the document usage scenario, use the document path as the key. @@ -121,10 +115,11 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of // ... }) ``` - -3. During running, the internal service of UIAbility determines whether to create multiple instances. If the key is matched, the UIAbility instance bound to the key is started. Otherwise, a new UIAbility instance is created. - The launch type of SpecifiedAbility is set to **specified**. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to parse the input **want** parameter and obtain the custom parameter **instanceKey**. A string key identifier is returned through the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the AbilityStage instance. [If the returned key corresponds to a started UIAbility instance](mission-management-launch-type.md#fig14520125175314), that UIAbility instance is switched to the foreground and gains focus again. Otherwise, a new instance is created and started. - + +3. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to obtain the key of the UIAbility, because the launch type of SpecifiedAbility is set to **specified**. If a UIAbility instance matching the key exists, the system starts the UIAbility instance and invokes its [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback. Otherwise, the system creates a new UIAbility instance and invokes its [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks. + + In the sample code, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback parses the **want** parameter to obtain the custom parameter **instanceKey**. The service logic returns a key string based on **instanceKey** parameter to identify the UIAbility instance. If the returned key maps to a started UIAbility instance, the system pulls the UIAbility instance back to the foreground and obtains the focus. If the returned key does not map to a started UIAbility instance, the system creates a new UIAbility instance and starts it. + ```ts import AbilityStage from '@ohos.app.ability.AbilityStage'; @@ -133,7 +128,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. // In this example, SpecifiedAbility of module1 is returned. if (want.abilityName === 'SpecifiedAbility') { - // The returned string key is a custom string. + // The returned key string is a custom string. return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } @@ -141,22 +136,17 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of } } ``` - - > **NOTE** + + > **NOTE**
> > 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). - - For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage. - -The following steps are used as an example. + For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage. + + The following steps are used as an example. + 1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. - 2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2. - 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. - - 4. Return to the home screen and open file A again. UIAbility instance 2 is started. - - \ No newline at end of file + 4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance. diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index 14cb5c4652749c97dd6e50c4232b6f65fb6feaab..7e31ab130df2ba9eaf959d1bfb3ddccfb7172480 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -3,9 +3,11 @@ ## Overview -UIAbility has the UI and is mainly used for user interaction. +UIAbility is a type of application component that provides the UI for user interaction. -UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. A UIAbility component can implement a functional module through multiple pages. Each UIAbility component instance corresponds to a mission in **Recents**. +UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. An application can contain one or more UIAbility components. For example, for a payment application, you can use two UIAbility components to carry the entry and payment functionalities. You are advised to use one UIAbility component to carry the same functional module, with multiple pages (if necessary). + +Each UIAbility component instance is displayed as a mission in Recents. ## Privacy Statement Configuration @@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb } } ``` - -> **NOTE** -> -> For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3). - diff --git a/en/application-dev/application-models/windowextensionability.md b/en/application-dev/application-models/windowextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..069897ad02435070ac470f5d2d3d528c76b417e8 --- /dev/null +++ b/en/application-dev/application-models/windowextensionability.md @@ -0,0 +1,112 @@ +# WindowExtensionAbility + +[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application. + + +The WindowExtensionAbility component must be used together with the [AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md) to process services of the started application. WindowExtensionAbility is run in connection mode. A system application must use the AbilityComponent to start the WindowExtensionAbility component. + +Each ExtensionAbility has its own context. For WindowExtensionAbility, +the context is [WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md). + +> **NOTE** +> +> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md). +> + + +## Setting an Embedded Ability (for System Applications Only) + +The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden. + +- The **onWindowReady()** callback is invoked when a window is created for the ability. + +- The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability. + +- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability. + + +**How to Develop** + +To implement an embedded application, manually create a WindowExtensionAbility in DevEco Studio as follows: + +1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **WindowExtAbility**. + +2. Right-click the **WindowExtAbility** directory, and choose **New > TypeScript File** to create a file named **WindowExtAbility.ts**. + +3. Open the **WindowExtAbility.ts** file and import the dependency package of **WindowExtensionAbility**. Customize a class that inherits from **WindowExtensionAbility** and implement the **onWindowReady()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks. + + ```ts + import Extension from '@ohos.application.WindowExtensionAbility' + + export default class WindowExtAbility extends Extension { + onWindowReady(window) { + window.loadContent('WindowExtAbility/pages/index1').then(() => { + window.getProperties().then((pro) => { + console.log("WindowExtension " + JSON.stringify(pro)); + }) + window.show(); + }) + } + + onConnect(want) { + console.info('JSWindowExtension onConnect ' + want.abilityName); + } + + onDisconnect(want) { + console.info('JSWindowExtension onDisconnect ' + want.abilityName); + } + } + ``` + +4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component. + + ```json + { + "module": { + "extensionAbilities": [ + { + "name": "WindowExtAbility", + "srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts", + "icon": "$media:icon", + "description": "WindowExtension", + "type": "window", + "visible": true, + } + ], + } + } + ``` + + +## Starting an Embedded Ability (for System Applications Only) + +System applications can load the created WindowExtensionAbility through the AbilityComponent. + +**How to Develop** + +1. To connect to an embedded application, add the AbilityComponent to the corresponding pages in the DevEco Studio project. + +2. Set **bundleName** and **abilityName** in the AbilityComponent. + +3. Set the width and height. The sample code is as follows: + +```ts +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"}) + .width(500) + .height(500) + } + .width('100%') + } + .height('100%') + .backgroundColor(0x64BB5c) + } +} +``` diff --git a/en/application-dev/application-test/arkxtest-guidelines.md b/en/application-dev/application-test/arkxtest-guidelines.md index bd82cae45fb4c673f014bcc13cfc02beb3853a2e..64edba5e9f4d4ebbd6b7bfbff44c4b01c8a67d4d 100644 --- a/en/application-dev/application-test/arkxtest-guidelines.md +++ b/en/application-dev/application-test/arkxtest-guidelines.md @@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below: ```js -import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest' +import {Driver,ON,Component,MatchPattern} from '@ohos.uitest' ``` Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases. @@ -131,16 +131,16 @@ export default function abilityTest() { expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) //ui test code - //init uidriver - var driver = await UiDriver.create(); + //init driver + var driver = await Driver.create(); await driver.delayMs(1000); - //find button by text 'Next' - var button = await driver.findComponent(BY.text('Next')); + //find button on text 'Next' + var button = await driver.findComponent(ON.text('Next')); //click button await button.click(); await driver.delayMs(1000); //check text - await driver.assertComponentExist(BY.text('after click')); + await driver.assertComponentExist(ON.text('after click')); await driver.pressBack(); done(); }) @@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b | itName | Test case to be executed. | {itName} | -s itName testAttributeIt | | timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 | | breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true | +| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true | | testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | | level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | -| size | Size of the test case to be executed. | small, medium, large | -s size small | +| size | Size of the test case to be executed. | small, medium, large | -s size small | | stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | **Running Commands** -> Configure hdc-related environment variables, and then perform the following: +> Before running commands in the CLI, make sure hdc-related environment variables have been configured. - Open the CLI. - Run the **aa test** commands. diff --git a/en/application-dev/application-test/figures/Execute.PNG b/en/application-dev/application-test/figures/Execute.PNG index ba96bdfdaf430249f3506153a45c6fe439eda5cc..0260b7983a13851dc1ef8e45928f952eb509a7d8 100644 Binary files a/en/application-dev/application-test/figures/Execute.PNG and b/en/application-dev/application-test/figures/Execute.PNG differ diff --git a/en/application-dev/connectivity/Readme-EN.md b/en/application-dev/connectivity/Readme-EN.md index 578e2a3c56c8a1f6cce377eb39ef9a7756d74491..7176cb8fb438cbe8beec5b36bdd290c0b01bbd1f 100755 --- a/en/application-dev/connectivity/Readme-EN.md +++ b/en/application-dev/connectivity/Readme-EN.md @@ -5,6 +5,10 @@ - [HTTP Data Request](http-request.md) - [WebSocket Connection](websocket-connection.md) - [Socket Connection](socket-connection.md) + - [Network Policy Management](net-policy-management.md) + - [Network Sharing](net-sharing.md) + - [Ethernet Connection](net-ethernet.md) + - [Network Connection Management](net-connection-manager.md) - IPC & RPC - [IPC & RPC Overview](ipc-rpc-overview.md) - [IPC & RPC Development](ipc-rpc-development-guideline.md) diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..1eddb3b5bbe47cb4d02123986647955d0492629e --- /dev/null +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -0,0 +1,246 @@ +# Network Connection Management + +## Introduction +The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md). + +## Basic Concepts +- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. +- Consumer: a user of data networks, for example, an application or a system service. +- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection. +- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes. + +## **Constraints** +- Programming language: C++ and JS +- System: Linux kernel +- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## When to Use +Typical application scenarios of network connection management are as follows: +- Subscribing to status changes of the specified network +- Obtaining the list of all registered networks +- Querying network connection information based on the data network +- Resolving the domain name of a network to obtain all IP addresses + +The following describes the development procedure specific to each application scenario. +## Available APIs +For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getGlobalHttpProxy10+(callback: AsyncCallback\): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function setGlobalHttpProxy10+(httpProxy: HttpProxy, callback: AsyncCallback): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getAppNet9+(callback: AsyncCallback\): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function setAppNet9+(netHandle: NetHandle, callback: AsyncCallback\): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getDefaultNetSync9+(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.| +| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getAllNets(callback: AsyncCallback\>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function isDefaultNetMetered9+(callback: AsyncCallback): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.| +| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\): void; |Subscribes to **netAvailable** events.| +| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\): void; |Subscribes to **netLost** events.| +| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\): void; |Subscribes to **netUnavailable** events.| +| ohos.net.connection.NetConnection | register(callback: AsyncCallback\): void; |Registers an observer for the default network or the network specified in **createNetConnection**.| +| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.| + +## Subscribing to Status Changes of the Specified Network + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used. + +3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**. + +4. Call **conn.register()** to subscribe to network status changes of the specified network. + +5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event. + +6. Call **conn.unregister()** to unsubscribe from the network status changes if required. + +```js + // Import the connection namespace. + import connection from '@ohos.net.connection' + + let netCap = { + // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. + bearerTypes: [connection.NetBearType.BEARER_CELLULAR], + // Set the network capability to INTERNET. + networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], + }; + let netSpec = { + netCapabilities: netCap, + }; + + // Set the timeout value to 10s. The default value is 0. + let timeout = 10 * 1000; + + // Create a NetConnection object. + let conn = connection.createNetConnection(netSpec, timeout); + + // Listen to network status change events. If the network is available, an on_netAvailable event is returned. + conn.on('netAvailable', (data=> { + console.log("net is available, netId is " + data.netId); + })); + + // Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. + conn.on('netUnavailable', (data=> { + console.log("net is unavailable, netId is " + data.netId); + })); + + // Register an observer for network status changes. + conn.register((err, data) => {}); + + // Unregister the observer for network status changes. + conn.unregister((err, data) => {}); +``` + +## Obtaining the List of All Registered Networks + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getAllNets** to obtain the list of all connected networks. + +```js + // Import the connection namespace. + import connection from '@ohos.net.connection' + + // Obtain the list of all connected networks. + connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } + }) +``` + +## Querying Network Capability Information and Connection Information of Specified Data Network + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\**. + +3. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities. + +4. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**. + +```js + // Import the connection namespace. + import connection from '@ohos.net.connection' + + // Call getDefaultNet to obtain the default data network specified by **NetHandle**. + connection.getDefaultNet((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netHandle = data; + } + }) + + // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities. + connection.getNetCapabilities(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + + // Obtain the network type via bearerTypes. + for (let item of data.bearerTypes) { + if (item == 0) { + // Cellular network + console.log(JSON.stringify("BEARER_CELLULAR")); + } else if (item == 1) { + // Wi-Fi network + console.log(JSON.stringify("BEARER_WIFI")); + } else if (item == 3) { + // Ethernet network + console.log(JSON.stringify("BEARER_ETHERNET")); + } + } + + // Obtain the specific network capabilities via networkCap. + for (let item of data.networkCap) { + if (item == 0) { + // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. + console.log(JSON.stringify("NET_CAPABILITY_MMS")); + } else if (item == 11) { + // The network traffic is not metered. + console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); + } else if (item == 12) { + // The network has the Internet access capability, which is set by the network provider. + console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); + } else if (item == 15) { + // The network does not use a Virtual Private Network (VPN). + console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); + } else if (item == 16) { + // The Internet access capability of the network is successfully verified by the connection management module. + console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); + } + } + }) + + // Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. + connection.getConnectionProperties(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + + // Call getAllNets to obtain the list of all connected networks via Array. + connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } + }) + + for (let item of this.netList) { + // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. + connection.getNetCapabilities(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + + // Obtain the connection information of the network specified by each netHandle on the network list cyclically. + connection.getConnectionProperties(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + } +``` + +## Resolving the domain name of a network to obtain all IP addresses + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses. + +```js + // Import the connection namespace. + import connection from '@ohos.net.connection' + + // Use the default network to resolve the host name to obtain the list of all IP addresses. + connection.getAddressesByName(this.host, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) +``` diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..85c4ef4fc15f4c2228eb8351ddb5cd730ff5fe94 --- /dev/null +++ b/en/application-dev/connectivity/net-ethernet.md @@ -0,0 +1,140 @@ +# Ethernet Connection + +## Introduction +The Ethernet Connection module allows a device to access the Internet through a network cable. +After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md). + +## **Constraints** +- Programming language: C++ and JS +- System: Linux kernel +- 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. + +## When to Use +Typical application scenarios of Ethernet connection are as follows: +- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access +- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access. + +The following describes the development procedure specific to each application scenario. + +## Available APIs +For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void | Configures the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.| +| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.| +| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.| +| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.| + +## Ethernet Connection – DHCP Mode + +1. Use a network cable to connect the device to a network port. +2. Import the **ethernet** namespace from **@ohos.net.ethernet**. +3. Call **getAllActiveIfaces** to obtain the list of all active network ports, for example, **eth0** and **eth1**. +4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active. +5. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. By default, an unconfigured Ethernet network uses the DHCP mode, in which the Ethernet network obtains the automatically assigned network attributes. + +```js + // Import the ethernet namespace from @ohos.net.ethernet. + import ethernet from '@ohos.net.ethernet' + + // Call getAllActiveIfaces to obtain the list of all active network ports. + ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } + }); + + // Call isIfaceActive to check whether the specified network port is active. + ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } + }); + + // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. + ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } + }); +``` +## Ethernet Connection – Static Mode + +### How to Develop + +1. Use a network cable to connect the device to a network port. +2. Import the **ethernet** namespace from **@ohos.net.ethernet**. +3. Call **getAllActiveIfaces** in user mode to obtain the list of all active network ports, for example, **eth0** and **eth1**. +4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active. +5. Call **setIfaceConfig** in user mode to set the **eth0** port to the static mode, in which you need to manually assign the network attributes (including the IP address, subnet mask, gateway, and DNS). +6. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. + +```js + // Import the ethernet namespace from @ohos.net.ethernet. + import ethernet from '@ohos.net.ethernet' + + // Call getAllActiveIfaces to obtain the list of all active network ports. + ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } + }); + + // Call isIfaceActive to check whether the specified network port is active. + ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } + }); + + // Call setIfaceConfig to configure the network attributes of the specified Ethernet network. + ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", + gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } + }); + + // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. + ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } + }); +``` diff --git a/en/application-dev/connectivity/net-mgmt-overview.md b/en/application-dev/connectivity/net-mgmt-overview.md index 3c8eeb552b811344396afcc6e5316e5daa24ee8b..0ad30c35cc9b4d5e90b2c8fe90cac7ca2e413a57 100644 --- a/en/application-dev/connectivity/net-mgmt-overview.md +++ b/en/application-dev/connectivity/net-mgmt-overview.md @@ -2,15 +2,19 @@ Network management functions include: -- [HTTP Data Request](http-request.md): Initiates a data request through HTTP. -- [WebSocket Connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. -- [Socket Connection](socket-connection.md): Transmits data through Socket. +- [HTTP data request](http-request.md): Initiates a data request through HTTP. +- [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. +- [Socket connection](socket-connection.md): Transmits data through Socket. +- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed. +- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. +- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. +- [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. ## Constraints To use the functions of the network management module, you must obtain the permissions listed in the following table. -| Permission | Description | +| Permission | Description | | -------------------------------- | -------------------------------------- | | ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. | | ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. | diff --git a/en/application-dev/connectivity/net-policy-management.md b/en/application-dev/connectivity/net-policy-management.md new file mode 100644 index 0000000000000000000000000000000000000000..6450bd671e565fdffafb7eeed499e123893a45a3 --- /dev/null +++ b/en/application-dev/connectivity/net-policy-management.md @@ -0,0 +1,402 @@ +# Network Policy Management + +## Introduction + +The Network Policy Management module allows you to restrict network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and to reset network policies as needed. + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-policy.md). + +## Basic Concepts + +- Sleep mode: A mode in which the system shuts down some idle components and peripherals to enter the low-power mode and restricts some applications from accessing the network. +- Power-saving mode: A mode in which the system disables certain functions and features to save power. When this mode is enabled, the system performance deteriorates and some applications are restricted from accessing the network. +- Traffic-saving mode: A mode in which the system restricts background applications that use the metering network. It is equivalent to the background network policy. +- Cellular network: A mobile communication network. +- Metering network: A mobile network with preconfigured traffic quota, WLAN network, or Ethernet network. + +## **Constraints** + +- Programming language: C++ and JS +- System: Linux kernel +- 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. + +## When to Use + +Typical application scenarios of network policy management are as follows: + +- Managing the metering network policy: Set the metering network quota and obtain the configured metering network policy. +- Managing network access for an application in the background: Set and obtain the status of the background network restriction switch, and check whether the application indicated by the specified UID can access the network in the background. +- Managing the metering network access policy: Set and obtain the policy for the application indicated by the specified UID to access the metering network, and obtain the UIDs of the applications for which the policy is configured. +- Restoring network policies +- Checking whether an application indicated by the specified UID can access a metering or non-metering network +- Adding a UID to or removing a UID from the sleep mode allowlist, and obtaining the sleep mode allowlist +- Adding a UID to or removing a UID from the power-saving mode allowlist, and obtaining the power-saving mode allowlist +- Updating the network notification policy + +The following describes the development procedure specific to each application scenario. + +## Available APIs + +For the complete list of APIs and example code, see [Network Policy Management](../reference/apis/js-apis-net-policy.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.policy | function setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void |Sets a background network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isBackgroundAllowed(callback: AsyncCallback\): void; |Obtains the background network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; |Sets an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getPolicyByUid(uid: number, callback: AsyncCallback\): void;| Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; | Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getNetQuotaPolicies(callback: AsyncCallback\>): void; |Obtains the network quota policies. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; |Sets an array of network quota policies. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; | Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; | Checks whether an application is allowed to access metering or non-metering networks. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; | Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getDeviceIdleAllowList(callback: AsyncCallback\>): void; | Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; | Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function resetPolicies(iccid: string, callback: AsyncCallback\): void; | Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; | Updates a reminder policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | Sets whether to add an application to the power-saving allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getPowerSaveAllowList(callback: AsyncCallback\>): void; | Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | Subscribes to policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | Unsubscribes from policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | Subscribes to rule changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | Unsubscribes from rule changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netMeteredIfacesChange", callback: Callback\>): void; | Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netMeteredIfacesChange", callback: Callback\>): void; | Unsubscribes from metered **iface** changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netQuotaPolicyChange", callback: Callback\>): void; | Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netQuotaPolicyChange", callback: Callback\>): void; | Unsubscribes from network quota policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netBackgroundPolicyChange", callback: Callback\): void; | Subscribes to background network policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netBackgroundPolicyChange", callback: Callback\): void; | Unsubscribes from background network policy changes. This API uses an asynchronous callback to return the result.| + +## Managing the Metering Network Policy + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setNetQuotaPolicies** to configure the metering network policy. + +3. Call **getNetQuotaPolicies** to obtain the configured metering network policy. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy'; + + addNetQuotaPolicy(){ + let param = { + // For details about the value of netType, see [NetBearType](../reference/apis/js-apis-net-connection.md#netbeartype). + netType:Number.parseInt(this.netType), + + // Integrated circuit card identifier (ICCID) of the SIM card on the metering cellular network. It is not available for an Ethernet or Wi-Fi network. + iccid:this.iccid, + + // Used together with ICCID on the metering cellular network. It is used independently on an Ethernet or Wi-Fi network. + ident:this.ident, + + // Metering start time, for example, M1, D1, and Y1. + periodDuration:this.periodDuration, + + // Set the traffic threshold for generating an alarm to an integer greater than 0. + warningBytes:Number.parseInt(this.warningBytes), + + // Set the traffic quota to an integer greater than 0. + limitBytes:Number.parseInt(this.limitBytes), + + // Specify whether the network is a metering network. The value true means a metering network and false means a non-metering network. + metered:Boolean(Number.parseInt(this.metered)),https://gitee.com/openharmony/docs/pulls/14404 + // For details about the action triggered after the traffic limit is reached, see [LimitAction](../reference/apis/js-apis-net-policy.md#limitaction). + limitAction:Number.parseInt(this.limitAction) + }; + this.netQuotaPolicyList.push(param); + }, + + // Subscribe to metered iface changes. + policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); + }); + + // Subscribe to metering network policy changes. + policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); + }); + + // Call setNetQuotaPolicies to configure the metering network policy. + setNetQuotaPolicies(){ + this.dialogType = DialogType.HIDE; + policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }); + }, + + // Call getNetQuotaPolicies to obtain the configured metering network policy. + getNetQuotaPolicies(){ + policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); + if(data){ + this.netQuotaPolicyList = data; + } + }); + }, + + // Unsubscribe from metered iface changes. + policy.off('netMeteredIfacesChange', (data) => { + this.log('off netMeteredIfacesChange: ' + JSON.stringify(data)); + }); + + // Unsubscribe from metering network policy changes. + policy.off('netQuotaPolicyChange', (data) => { + this.log('off netQuotaPolicyChange: ' + JSON.stringify(data)); + }); +``` + +## Managing Network Access for an Application in the Background + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setBackgroundAllowed** to enable or disable the background network restriction switch. + +3. Call **isBackgroundAllowed** to check whether the background network restriction switch is enabled or disabled. + +4. Call **getBackgroundPolicyByUid** to check whether the application indicated b the specified UID can access the network in the background. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Subscribe to background network policy changes. + policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); + }); + + // Call setBackgroundAllowed to enable or disable the background network restriction switch. + setBackgroundAllowed() { + policy.setBackgroundAllowed(Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call isBackgroundAllowed to check whether the background network restriction switch is enabled or disabled. + isBackgroundAllowed() { + policy.isBackgroundAllowed((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getBackgroundPolicyByUid to check whether the application indicated b the specified UID can access the network in the background. + getBackgroundPolicyByUid() { + policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Unsubscribe from background network policy changes. + policy.off('netBackgroundPolicyChange', (data) => { + this.log('off netBackgroundPolicyChange: ' + JSON.stringify(data)); + }); +``` + +## Managing the Metering Network Access Policy + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setPolicyByUid** to set whether the application indicated by the specified UID can access the network in the background. + +3. Call **getPolicyByUid** to check whether the metering network access policy for the application indicated by the specified UID. + +4. Call **getUidsByPolicy** to obtain the UIDs of the applications for which the metering network access policy is configured. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Subscribe to policy changes of the application indicated by the specified UID. + policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); + }); + + // Subscribe to rule changes of the application indicated by the specified UID. + policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); + }); + + // Call setPolicyByUid to set whether the application indicated by the specified UID can access the network in the background. + setPolicyByUid() { + let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) + } + policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getPolicyByUid to check whether the metering network access policy for the application indicated by the specified UID. + getPolicyByUid() { + policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getUidsByPolicy to obtain the UIDs of the applications for which the metering network access policy is configured. + getUidsByPolicy(){ + policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Unsubscribe from policy changes of the application indicated by the specified UID. + policy.off('netUidPolicyChange', (data) => { + this.log('off netUidPolicyChange: ' + JSON.stringify(data)); + }); + + // Unsubscribe from rule changes of the application indicated by the specified UID. + policy.off('netUidRuleChange', (data) => { + this.log('off netUidRuleChange: ' + JSON.stringify(data)); + }); + +``` + +## Restoring Network Policies + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **restoreAllPolicies** to restore all network policies. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call restoreAllPolicies to restore all network policies. + restoreAllPolicies(){ + policy.restoreAllPolicies(this.firstParam, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Checking Access to a Metering or Non-metering Network + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **isUidNetAllowed** to check whether the UID can access the metering or non-metering network. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call isUidNetAllowed to check whether the application indicated by the specified UID can access the metering or non-metering network. + isUidNetAllowedIsMetered(){ + let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) + } + policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Managing the Sleep Mode Allowlist + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setDeviceIdleAllowList** to add a UID to or remove a UID from the sleep mode allowlist. + +3. Call **getDeviceIdleAllowList** to obtain the UIDs added to the sleep mode allowlist. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call setDeviceIdleAllowList to add a UID to or remove a UID from the sleep mode allowlist. + setDeviceIdleAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getDeviceIdleAllowList to obtain the UIDs added to the sleep mode allowlist. + getDeviceIdleAllowList(){ + policy.getDeviceIdleAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Managing the Power-saving Mode Allowlist + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. +2. Call **setPowerSaveAllowList** to add a UID to or remove a UID from the power-saving mode allowlist. +3. Call **getPowerSaveAllowList** to obtain the UIDs added to the power-saving mode allowlist. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call setPowerSaveAllowList to add a UID to or remove a UID from the power-saving mode allowlist. + setPowerSaveAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getPowerSaveAllowList to obtain the UIDs added to the power-saving mode allowlist. + getPowerSaveAllowList(){ + policy.getPowerSaveAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Updating the Network Notification Policy + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **updateRemindPolicy** to update the network notification policy. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call updateRemindPolicy to update the network notification policy. + updateRemindPolicy() { + let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType + } + policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..d81e8f59ecfb538ececb78afc83941d52f330eda --- /dev/null +++ b/en/application-dev/connectivity/net-sharing.md @@ -0,0 +1,130 @@ +# Network Sharing + +## Introduction +The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md). + +## Basic Concepts +- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot. +- Bluetooth sharing: Shares the network through Bluetooth. +- USB tethering: Shares the network using a USB flash drive. + +## **Constraints** +- Programming language: C++ and JS +- System: Linux kernel +- 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. + +## When to Use +Typical network sharing scenarios are as follows: +- Enabling network sharing +- Disabling network sharing +- Obtaining the data traffic of the shared network + +The following describes the development procedure specific to each application scenario. +## Available APIs +For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\): void; | Checks whether the system supports network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function isSharing(callback: AsyncCallback\): void; | Checks whether network sharing is active. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | Starts network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | Stops network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\): void; | Obtains the received data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\): void; | Obtains the sent data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\): void; | Obtains the total data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void; | Obtains the names of network interface cards (NICs) in the specified network sharing state.. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void; | Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void; | Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\): void; | Subscribes to network sharing state changes.| +| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\): void; | Unsubscribes from network sharing state changes.| +| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Subscribes to network sharing state changes of the specified NIC.| +| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Unsubscribes from network sharing state changes of the specified NIC.| +| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\): void; | Subscribes to upstream NIC changes.| +| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\): void; | Unsubscribes from upstream NIC changes.| + +## Enabling Network Sharing + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Subscribe to network sharing state changes. +3. Call **startSharing** to start network sharing of the specified type. +4. Return the callback for successfully starting network sharing. + +```js + // Import the sharing namespace from @ohos.net.sharing. + import sharing from '@ohos.net.sharing' + + // Subscribe to network sharing state changes. + sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // Call startSharing to start network sharing of the specified type. + sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## Disabling network sharing + +### How to Develop + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Subscribe to network sharing state changes. +3. Call **stopSharing** to stop network sharing of the specified type. +4. Return the callback for successfully stopping network sharing. + +```js + // Import the sharing namespace from @ohos.net.sharing. + import sharing from '@ohos.net.sharing' + + // Subscribe to network sharing state changes. + sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // Call stopSharing to stop network sharing of the specified type. + sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## Obtaining the data traffic of the shared network + +### How to Develop + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Call **startSharing** to start network sharing of the specified type. +3. Call **getStatsTotalBytes** to obtain the data traffic generated during data sharing. +4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing. + +```js + // Import the sharing namespace from @ohos.net.sharing. + import sharing from '@ohos.net.sharing' + + // Call startSharing to start network sharing of the specified type. + sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); + + // Call getStatsTotalBytes to obtain the data traffic generated during data sharing. + sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing. + sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); + + // Call getStatsTotalBytes again. The data volume of network sharing has been cleared. + sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); +``` diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index da5bea318e2b60da5641b9cf01ee73c926802c16..96c802d565d0e58201b627d18be1e59093919a07 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,46 +1,82 @@ # Socket Connection +## Introduction -## Use Cases +The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol. -Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported. +## Basic Concepts +- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network. +- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable. +- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol. +- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs. + +## When to Use + +Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows: + +- Implementing data transmission over TCP/UDP Socket connections +- Implementing encrypted data transmission over TLS Socket connections ## Available APIs -The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs. +For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md). + +Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs. -| API| Description | +| API| Description| | -------- | -------- | -| constructUDPSocketInstance() | Creates a **UDPSocket** object. | -| constructTCPSocketInstance() | Creates a **TCPSocket** object. | -| bind() | Binds the IP address and port number. | +| constructUDPSocketInstance() | Creates a **UDPSocket** object.| +| constructTCPSocketInstance() | Creates a **TCPSocket** object.| +| bind() | Binds the IP address and port number.| | send() | Sends data.| -| close() | Closes a Socket connection. | -| getState() | Obtains the Socket connection status. | -| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | -| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. | -| on(type: 'message') | Enables listening for **message** events of the Socket connection. | -| off(type: 'message') | Disables listening for **message** events of the Socket connection. | -| on(type: 'close') | Enables listening for **close** events of the Socket connection. | -| off(type: 'close') | Disables listening for **close** events of the Socket connection. | -| on(type: 'error') | Enables listening for **error** events of the Socket connection. | -| off(type: 'error') | Disables listening for **error** events of the Socket connection. | -| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. | -| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. | -| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. | -| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. | +| close() | Closes a Socket connection.| +| getState() | Obtains the Socket connection status.| +| connect() | Connects to the specified IP address and port. This function is supported only for TCP.| +| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.| +| on(type: 'message') | Subscribes to **message** events of the Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the Socket connection.| +| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.| +| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. | +| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. | +| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. | +| off(type: 'connect') | Unsubscribes from **connect** events of the TCP Socket connection.| +TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. + +| API| Description| +| -------- | -------- | +| bind() | Binds the IP address and port number.| +| close(type: 'error') | Closes a Socket connection.| +| connect() | Sets up a connection to the specified IP address and port number.| +| getCertificate() | Obtains an object representing the local certificate.| +| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.| +| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.| +| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.| +| getRemoteCertificate() | Obtains an object representing a peer certificate.| +| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| +| getState() | Obtains the TLS Socket connection status.| +| off(type: 'close') | Unsubscribes from **close** events of the TLS Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the TLS Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the TLS Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the TLS Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the TLS Socket connection.| +| on(type: 'message') | Subscribes to **message** events of the TLS Socket connection.| +| send() | Sends data.| +| setExtraOptions() | Sets other properties of the TLS Socket connection.| -## How to Develop +## Transmitting Data over TCP/UDP Socket Connections -The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example. +The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example. -1. Import the required Socket module. +1. Import the required **socket** module. 2. Create a **TCPSocket** object. -3. (Optional) Enable listening for TCPSocket events. +3. (Optional) Subscribe to TCP Socket connection events. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. @@ -48,15 +84,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th 6. Send data. -7. Enable the TCPSocket connection to be automatically closed after use. - +7. Enable the TCP Socket connection to be automatically closed after use. + ```js import socket from '@ohos.net.socket' - + // Create a TCPSocket object. let tcp = socket.constructTCPSocketInstance(); - - // Enable listening for TCPSocket events. + + // Subscribe to TCP Socket connection events. tcp.on('message', value => { console.log("on message") let buffer = value.message @@ -73,7 +109,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.on('close', () => { console.log("on close") }); - + // Bind the local IP address and port number. let bindAddress = { address: '192.168.xx.xx', @@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('bind success'); + // Set up a connection to the specified IP address and port number. let connectAddress = { address: '192.168.xx.xx', @@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('connect success'); + // Send data. tcp.send({ data: 'Hello, server!' @@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th }) }); }); - // Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events. + + // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. setTimeout(() => { tcp.close((err) => { console.log('close socket.') @@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.off('close'); }, 30 * 1000); ``` + +## Implementing Encrypted Data Transmission over TLS Socket Connections + +### How to Develop + +TLS Socket connection process on the client: + +1. Import the required **socket** module. + +2. Bind the IP address and port number of the server. + +3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. + +4. Create a **TLSSocket** object. + +5. (Optional) Subscribe to TLS Socket connection events. + +6. Send data. + +7. Enable the TLS Socket connection to be automatically closed after use. + +```js + import socket from '@ohos.net.socket' + + // Create a TLS Socket connection (for two-way authentication). + let tlsTwoWay = socket.constructTLSSocketInstance(); + + // Subscribe to TLS Socket connection events. + tcp.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.on('close', () => { + console.log("on close") + }); + + // Bind the local IP address and port number. + tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + }); + + // Set the communication parameters. + let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + + // Set up a connection to the specified IP address and port number. + address: { + address: "192.168.xx.xxx", + port: xxxx, // Port + family: 1, + }, + + // Set the parameters used for authentication during communication. + secureOptions: { + key: "xxxx", // Key + cert: "xxxx", // Digital certificate + ca: ["xxxx"], // CA certificate + passwd: "xxxx", // Password for generating the key + protocols: [socket.Protocol.TLSv12], // Communication protocol + useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm + cipherSuite: "AES256-SHA256", // Cipher suite + }, + }; + + // Set up a connection. + tlsTwoWay.connect(options, (err, data) => { + console.error(err); + console.log(data); + }); + + // Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); + + // Create a TLS Socket connection (for one-way authentication). + let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication + + // Subscribe to TLS Socket connection events. + tcp.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0;i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.on('close', () => { + console.log("on close") + }); + + // Bind the local IP address and port number. + tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + }); + + // Set the communication parameters. + let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx","xxxx"], // CA certificate + cipherSuite: "AES256-SHA256", // Cipher suite + }, + }; + + // Set up a connection. + tlsOneWay.connect(oneWayOptions, (err, data) => { + console.error(err); + console.log(data); + }); + + // Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); +``` + +## Samples + +The following samples are provided to help you better understand how to develop Socket connection features: +- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) +- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) +- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 1f25dccf2a36f3bbedb5728291e8e11b3292476e..580811158051b5b6d5d2137f4b14654a46e891b9 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -34,7 +34,7 @@ There are two roles in **DataShare**: - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data consumer: accesses the data provided by the provider using **DataShareHelper**. -### Data Provider Application Development (Only for System Applications) +### Data Provider Application Development (for System Applications Only) [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required. diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index b72874536b968593cbb7a3c8d5fd865eb1720b35..70c0ee209975ff3322210041e123afbeec3b5e6f 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KvManager** object for database management. | +| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** object for database management. | | getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.| | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | | delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | @@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p bundleName: 'com.example.datamanagertest', context:context, } - distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`); - return; - } - console.log('Created KVManager successfully'); - kvManager = manager; - }); + kvManager = distributedKVStore.createKVManager(kvManagerConfig); + console.log("Created KVManager successfully"); } catch (e) { - console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`Failed to create KVManager. Code is ${e.code}, message is ${e.message}`); } ``` @@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p }; kvManager.getKVStore('storeId', options, function (err, store) { if (err) { - console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore: code is ${err.code}, message is ${err.message}`); return; } console.log('Obtained KVStore successfully'); kvStore = store; }); } catch (e) { - console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`); } ``` @@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p console.log(`dataChange callback call data: ${data}`); }); }catch(e){ - console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occured. Code is ${e.code}, message is ${e.message}`); } ``` @@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.error(`Failed to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`); return; } - console.log('Put data successfully'); + console.log("Put data successfully"); }); }catch (e) { - console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`); } ``` @@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.error(`Failed to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`); return; } - console.log('Put data successfully'); + console.log("Put data successfully"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.error(`Failed to get data.code is ${err.code},message is ${err.message}`); + console.error(`Failed to obtain data. Code is ${err.code}, message is ${err.message}`); return; } console.log(`Obtained data successfully:${data}`); }); }); }catch (e) { - console.error(`Failed to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to obtain data. Code is ${e.code}, message is ${e.message}`); } ``` @@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p // 1000 indicates that the maximum delay is 1000 ms. kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); } catch (e) { - console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`); } } }); diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index e5c9faa1477565541a94076e2fb568e69b2f5cf6..724e273675061c4b6969fb3fcd6f6cbdd984a15f 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file ```ts // Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'; - let context = null; let preferences = null; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context; + onWindowStageCreate(windowStage) { + let promise = data_preferences.getPreferences(this.context, 'mystore'); + promise.then((pref) => { + preferences = pref; + }).catch((err) => { + console.info("Failed to get the preferences."); + }) } } - let promise = data_preferences.getPreferences(context, 'mystore'); - promise.then((pref) => { - preferences = pref; - }).catch((err) => { - console.info("Failed to get the preferences."); - }) ``` 3. Write data. diff --git a/en/application-dev/device/Readme-EN.md b/en/application-dev/device/Readme-EN.md index abf5154a8caa1473367960eea7b9118598ce706a..6ce8d1b16951d5fb739d97c102cb8d3be3f628d7 100644 --- a/en/application-dev/device/Readme-EN.md +++ b/en/application-dev/device/Readme-EN.md @@ -1,19 +1,21 @@ -# Device +# Device Management +- USB Service + - [USB Service Overview](usb-overview.md) + - [USB Service Development](usb-guidelines.md) - Location - [Location Service Development](location-guidelines.md) -- Multimodal Input - - [Input Device Development](inputdevice-guidelines.md) - - [Mouse Pointer Development](pointerstyle-guidelines.md) - Sensor - [Sensor Overview](sensor-overview.md) - [Sensor Development](sensor-guidelines.md) +- Vibrator + - [Vibrator Overview](vibrator-overview.md) + - [Vibrator Development](vibrator-guidelines.md) +- Multimodal Input + - [Input Device Development](inputdevice-guidelines.md) + - [Mouse Pointer Development](pointerstyle-guidelines.md) - Update Service - [Sample Server Overview](sample-server-overview.md) - [Sample Server Development](sample-server-guidelines.md) -- USB Service - - [USB Service Overview](usb-overview.md) - - [USB Service Development](usb-guidelines.md) -- Vibrator - - [Vibrator Overview](vibrator-overview.md) - - [Vibrator Development](vibrator-guidelines.md) \ No newline at end of file +- Stationary + - [Stationary Development](stationary-guidelines.md) diff --git a/en/application-dev/device/pointerstyle-guidelines.md b/en/application-dev/device/pointerstyle-guidelines.md index cecab92b282e2da7a3bb966bcedeefa84768f22e..bcc09093eed4440a0c5e62c5d4cfe37a3f954c87 100644 --- a/en/application-dev/device/pointerstyle-guidelines.md +++ b/en/application-dev/device/pointerstyle-guidelines.md @@ -15,11 +15,11 @@ import pointer from '@ohos.multimodalInput.pointer'; The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md). | Instance | API | Description | -| ------- | ------------------------------------------------------------ | --------------------------------------------------------------- | -| pointer | function isPointerVisible(callback: AsyncCallback\): void; | Checks the visible status of the mouse pointer. | -| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally. | +| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| pointer | function isPointerVisible(callback: AsyncCallback\): void; | Checks the visible status of the mouse pointer. | +| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally.| | pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. | -| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\): void; | Obtains the mouse pointer style. | +| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\): void; | Obtains the mouse pointer style. | ## Hiding the Mouse Pointer @@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co 5. Set the mouse pointer to the default style. ```js +import pointer from '@ohos.multimodalInput.pointer'; import window from '@ohos.window'; // 1. Enable the color pickup function. // 2. Obtain the window ID. -window.getTopWindow((error, windowClass) => { - windowClass.getProperties((error, data) => { - var windowId = data.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - // 3. Set the mouse pointer to the color picker style. - pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { - console.log(`Successfully set mouse pointer style`); - }); - } catch (error) { - console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); - } - }); +window.getLastWindow(this.context, (error, windowClass) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + var windowId = windowClass.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 3. Set the mouse pointer to the color picker style. + pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`); + } }); // 4. End color pickup. -window.getTopWindow((error, windowClass) => { - windowClass.getProperties((error, data) => { - var windowId = data.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - // 5. Set the mouse pointer to the default style. - pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { - console.log(`Successfully set mouse pointer style`); - }); - } catch (error) { - console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); - } - }); +window.getLastWindow(this.context, (error, windowClass) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + var windowId = windowClass.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 5. Set the mouse pointer to the default style. + pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`); + } }); ``` diff --git a/en/application-dev/device/stationary-guidelines.md b/en/application-dev/device/stationary-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..9f6693027a29f48c2c434b842df74beb5209f319 --- /dev/null +++ b/en/application-dev/device/stationary-guidelines.md @@ -0,0 +1,84 @@ +# Stationary Development + + +## When to Use + +An application can call the **Stationary** module to obtain the device status, for example, whether the device is absolutely or relatively still. + +For details about the APIs, see [Stationary](../reference/apis/js-apis-stationary.md). + +## Device Status Type Parameters + +| Name| Description| +| -------- | -------- | +| still | Absolutely still.| +| relativeStill | Relatively still.| + +## Parameters for Subscribing to Device Status events + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Event indicating entering device status. | +| EXIT | 2 | Event indicating exiting device status.| +| ENTER_EXIT | 3 | Event indicating entering and exiting device status.| + +## Returned Device Status Parameters + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Entering device status. | +| EXIT | 2 | Exiting device status.| + +## Available APIs + +| Module | Name | Description | +| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void | Subscribes to the device status. This API uses an asynchronous callback to return the result.| +| ohos.stationary | once(activity: ActivityType, callback: Callback<ActivityResponse>): void | Obtains the device status. This API uses an asynchronous callback to return the result.| +| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void | Unsubscribes from the device status. | + +## Constraints + +The device must support the acceleration sensor. + +## How to Develop + +1. Subscribe to the event indicating entering the absolute still state, and the event is reported every 1 second. + + ```js + import stationary from '@ohos.stationary'; + var reportLatencyNs = 1000000000; + try { + stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` + +2. Obtain the event indicating entering the absolute still state. + + ```js + import stationary from '@ohos.stationary'; + try { + stationary.once('still', (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` + +3. Unsubscribe from the event indicating entering the absolute still state. + + ```js + import stationary from '@ohos.stationary'; + try { + stationary.off('still', stationary.ActivityEvent.ENTER, (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index 36b08b2acd96e2d65fc14a936f1c3e9c9dd31a88..c028f5be4890c476bab762cfc8b0f0d12d9fdda8 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -16,6 +16,10 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md | ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.| | ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise<void> | Stops vibration in the specified mode. This API uses a promise to return the result. | | ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | +| ohos.vibrator | stopVibration(): Promise<void> | Stops vibration in all modes. This API uses a promise to return the result. | +| ohos.vibrator | stopVibration(callback: AsyncCallback<void>): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. | +| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean> | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | +| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | ## How to Develop @@ -27,7 +31,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ```js import vibrator from '@ohos.vibrator'; try { - vibrator.startVibration({ + vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission. type: 'time', duration: 1000, }, { @@ -50,7 +54,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ```js import vibrator from '@ohos.vibrator'; try { - // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission. vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { if (error) { console.log('error.code' + error.code + 'error.message' + error.message); @@ -62,3 +66,72 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` + +4. Stop vibration in all modes. + + ```js + import vibrator from '@ohos.vibrator'; + // To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. + try { + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; + } + console.log('Callback returned to indicate a successful vibration.'); + }); + // Stop vibration in all modes. + vibrator.stopVibration(function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + return; + } + console.log('Callback returned to indicate successful.'); + }) + } catch (error) { + console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + } + ``` + +5. Check whether the passed effect ID is supported. + + ```js + import vibrator from '@ohos.vibrator'; + try { + // Check whether 'haptic.clock.timer' is supported. + vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { + if (err) { + console.error('isSupportEffect failed, error:' + JSON.stringify(err)); + return; + } + console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); + if (state) { + try { + vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission. + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }, (error) => { + if(error) { + console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error)); + } else { + console.log('haptic.clock.timer vibrator success'); + } + }); + } catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); + } + } + }) + } catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); + } + ``` diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index 4ed700a49b94ef0c296ec27eaf9c5cde96575234..c6b449f197ba66d8bd6f4021abffe6ce31a69028 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,13 +1,9 @@ # DFX -- Application Event Logging - - [Development of Application Event Logging](hiappevent-guidelines.md) -- Distributed Call Chain Tracing - - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) -- HiLog - - [HiLog Development](hilog-guidelines.md) -- Performance Tracing - - [Development of Performance Tracing](hitracemeter-guidelines.md) +- [Development of Application Event Logging](hiappevent-guidelines.md) +- [Development of Performance Tracing](hitracemeter-guidelines.md) +- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) +- [HiLog Development (Native)](hilog-guidelines.md) - Error Management - [Development of Error Manager](errormanager-guidelines.md) - - [Development of Application Recovery](apprecovery-guidelines.md) + - [Development of Application Recovery](apprecovery-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index 667339c3b3dbaa101cfbda8eeacbc8f11c2fd03d..4679cfcfc78893590fe73eab770e49fc68a1a828 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F | API | Description | | ------------------------------------------------------------ | ---------------------------------------------------- | -| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| -| unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | -| unregisterErrorObserver(observerId: number): Promise\ | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | +| on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| +| off(type: "error", observerId: number, callback: AsyncCallback\): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | +| off(type: "error", observerId: number): Promise\ | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | -When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). +When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result codes-for-unregistering-an-observer). **Table 2** Description of the ErrorObserver API @@ -39,22 +39,23 @@ When an asynchronous callback is used, the return value can be processed directl import UIAbility from '@ohos.app.ability.UIAbility'; import errorManager from '@ohos.app.ability.errorManager'; -var registerId = -1; -var callback = { +let registerId = -1; +let callback = { onUnhandledException: function (errMsg) { console.log(errMsg); } } -export default class EntryAbility extends Ability { + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log("[Demo] EntryAbility onCreate") - registerId = errorManager.registerErrorObserver(callback); + registerId = errorManager.on("error", callback); globalThis.abilityWant = want; } onDestroy() { console.log("[Demo] EntryAbility onDestroy") - errorManager.unregisterErrorObserver(registerId, (result) => { + errorManager.off("error", registerId, (result) => { console.log("[Demo] result " + result.code + ";" + result.message) }); } diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md index 4c7e2ecd4db6723a66930e624bd4b36b556330d1..1e310ef9312499bb131affb620ac7758e5033778 100644 --- a/en/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -136,7 +136,7 @@ async function copySandbox2Public() { console.error('file asset get failed, message = ' + err); } let fdPub = await fileAsset.open('rw'); - let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE); + let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE); await fs.copyFile(fdSand.fd, fdPub); await fileAsset.close(fdPub); await fs.close(fdSand.fd); @@ -174,7 +174,7 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); - media.createAsset(mediaType, "testFile.text", path).then((asset) => { + media.createAsset(mediaType, "testFile.txt", path).then((asset) => { console.info("createAsset successfully:" + JSON.stringify(asset)); }).catch((err) => { console.error("createAsset failed with error: " + err); diff --git a/en/application-dev/file-management/medialibrary-resource-guidelines.md b/en/application-dev/file-management/medialibrary-resource-guidelines.md index 7d120ec9a4fa9fd38ba92be97ee7fdd5a6f33816..054591847ffa156f5ee85cf5e2412b215750e283 100644 --- a/en/application-dev/file-management/medialibrary-resource-guidelines.md +++ b/en/application-dev/file-management/medialibrary-resource-guidelines.md @@ -42,14 +42,11 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - fetchFileResult.getFirstObject().then((fileAsset) => { + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.log('getFirstObject.displayName : ' + fileAsset.displayName); for (let i = 1; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject().then((fileAsset) => { - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }).catch((err) => { - console.error('Failed to get next object: ' + err); - }); + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } }).catch((err) => { console.error('Failed to get first object: ' + err); @@ -75,14 +72,11 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - fetchFileResult.getFirstObject().then((fileAsset) => { + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName); for (let i = 1; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject().then((fileAsset) => { - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }).catch((err) => { - console.error('Failed to get next object: ' + err); - }); + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } }).catch((err) => { console.error('Failed to get first object: ' + err); @@ -108,14 +102,11 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - fetchFileResult.getFirstObject().then((fileAsset) => { + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName); for (let i = 1; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject().then((fileAsset) => { - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }).catch((err) => { - console.error('Failed to get next object: ' + err); - }); + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } }).catch((err) => { console.error('Failed to get first object: ' + err); diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 8218f2561376c4119f66be0175c5c9ea16c7d024..e78bdb6437b26b8a30ee23f9fdec380087297b33 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t ## Obtaining and Setting i18n Information -The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch. +The following table lists the APIs used to configure information such as the system language, preferred language, country or region, 24-hour clock, and use of local digits. ### Available APIs @@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p | System | getPreferredLanguageList()9+ | Obtains the preferred language list. | | System | getFirstPreferredLanguage()9+ | Obtains the first language in the preferred language list. | | System | getAppPreferredLanguage()9+ | Obtains the preferred language of an application. | -| System | setUsingLocalDigit(flag: boolean)9+ | Sets whether to enable the local digit switch. | -| System | getUsingLocalDigit()9+ | Checks whether the local digit switch is turned on. | +| System | setUsingLocalDigit(flag: boolean)9+ | Specifies whether to enable use of local digits. | +| System | getUsingLocalDigit()9+ | Checks whether use of local digits is enabled. | | | isRTL(locale:string):boolean9+ | Checks whether the locale uses a right-to-left (RTL) language.| ### How to Develop 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Obtain and set the system language. @@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p I18n.System.setSystemLanguage("en"); // Set the system language to en. let language = I18n.System.getSystemLanguage(); // language = "en" } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p I18n.System.setSystemRegion("CN"); // Set the system country to CN. let region = I18n.System.getSystemRegion(); // region = "CN" } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p let rtl = I18n.isRTL("zh-CN"); // rtl = false rtl = I18n.isRTL("ar"); // rtl = true } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p I18n.System.set24HourClock(true); let hourClock = I18n.System.is24HourClock(); // hourClock = true } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p let sentenceCase = false; let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p let sentenceCase = false; let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p try { let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources. } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) Call **getUsingLocalDigit** to check whether the local digit switch is enabled. - Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". + Currently, use of local digits is supported only for the following languages: **ar**, **as**, **bn**, **fa**, **mr**, **my**, **ne**, **ur**. ```js try { I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. let status = I18n.System.getUsingLocalDigit(); // status = true } catch(error) { - console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`); } ``` @@ -220,14 +220,14 @@ try { | Calendar | getMinimalDaysInFirstWeek():number8+ | Obtains the minimum number of days in the first week of a year. | | Calendar | setMinimalDaysInFirstWeek(value:number): void8+ | Sets the minimum number of days in the first week of a year. | | Calendar | getDisplayName(locale:string):string8+ | Obtains the localized display of the **Calendar** object. | -| Calendar | isWeekend(date?:Date):boolean8+ | Checks whether the specified date in this **Calendar** object is a weekend. | +| Calendar | isWeekend(date?:Date):boolean8+ | Checks whether a given date is a weekend in the calendar. | ### How to Develop 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Instantiate a **Calendar** object. @@ -254,7 +254,7 @@ try { Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. ```js - calendar.set(2021, 12, 21, 6, 0, 0) + calendar.set(2021, 12, 21, 6, 0, 0); ``` 5. Set and obtain the time zone for the **Calendar** object. @@ -317,7 +317,7 @@ try { 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Instantiate a **PhoneNumberFormat** object. @@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Convert a measurement unit. @@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Instantiates an **IndexUtil** object. @@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. Call **addLocale** to add the alphabet index of a new locale to the current index list. ```js - indexUtil.addLocale("ar") + indexUtil.addLocale("ar"); ``` 5. Obtain the index of a string. @@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Instantiate a **BreakIterator** object. @@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc Call **getLineInstance** to instantiate a **BreakIterator** object. ```js - let locale = "en-US" + let locale = "en-US"; let breakIterator = I18n.getLineInstance(locale); ``` @@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Instantiate the **TimeZone** object, and obtain the time zone information. @@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Obtains the transliterator ID list. @@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Check the input character has a certain attribute. @@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to 1. Import the **i18n** module. ```js - import I18n from '@ohos.i18n' + import I18n from '@ohos.i18n'; ``` 2. Check the sequence of year, month, and day in a date. diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 609af84500cecb0ce5bda8409216b6957182885f..7274514385795ec42b6e81924e34e71070a71ebf 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiates a **Locale** object. @@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiate a **DateTimeFormat** object. @@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiate a **NumberFormat** object. @@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ```js let options = {compactDisplay: "short", notation: "compact"}; let numberFormat = new Intl.NumberFormat("zh-CN", options); - let number = 1234.5678 + let number = 1234.5678; let formatResult = numberFormat.format(number); // formatResult = "1235" ``` @@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiate a **Collator** object. @@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll let collator = new Intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. ```js @@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiate a **PluralRules** object. @@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou let pluralRules = new Intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). ```js let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou ```js let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); - let number = 1234.5678 + let number = 1234.5678; let categoryResult = pluralRules.select(number); // categoryResult = "other" ``` @@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou Importing an incorrect bundle can lead to unexpected API behavior. ```js - import Intl from '@ohos.intl' + import Intl from '@ohos.intl'; ``` 2. Instantiate a **RelativeTimeFormat** object. @@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou let relativeTimeFormat = new Intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). ```js let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); @@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou ```js let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let number = 2; - let unit = "year" + let unit = "year"; let formatResult = relativeTimeFormat.format(number, unit); // 2 years later ``` @@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou ```js let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let number = 2; - let unit = "year" + let unit = "year"; let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] ``` @@ -390,6 +390,4 @@ According to grammars in certain languages, the singular or plural form of a nou The following sample is provided to help you better understand how to develop internationalization capabilities: --[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) - --[`International`: Internationalization (ArkTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) +-[`International`: Internationalization (ArkTS) (API9) (Full SDK)] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 926a2718a48dcefd217e503932f9d9f997d1275e..f6902595cadbea27765ebf1812544821b3c68a09 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -12,10 +12,10 @@ - [Audio Routing and Device Management Development](audio-routing-manager.md) - [AVPlayer Development (Recommended)](avplayer-playback.md) - [AVRecorder Development (Recommended)](avrecorder.md) - - [Audio Playback Development](audio-playback.md) - - [Audio Recording Development](audio-recorder.md) - - [Video Playback Development](video-playback.md) - - [Video Recording Development](video-recorder.md) + - [Audio Playback Development (To Be Deprecated Soon)](audio-playback.md) + - [Audio Recording Development (To Be Deprecated Soon)](audio-recorder.md) + - [Video Playback Development (To Be Deprecated Soon)](video-playback.md) + - [Video Recording Development (To Be Deprecated Soon)](video-recorder.md) - AVSession - [AVSession Overview](avsession-overview.md) diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 8371b6248d71f48e9088da849dc36c3edb2be3cf..f7b01ce2a387af3471b297de329fe3267b9e9785 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -27,32 +27,43 @@ Before developing the audio data collection feature, configure the **ohos.permis For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). -1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. +1. Use **createAudioCapturer()** to create a global **AudioCapturer** instance. Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification. ```js - import audio from '@ohos.multimedia.audio'; + import audio from '@ohos.multimedia.audio'; + import fs from '@ohos.file.fs'; // It will be used for the call of the read function in step 3. + + // Perform a self-test on APIs related to audio rendering. + @Entry + @Component + struct AudioRenderer { + @State message: string = 'Hello World' + private audioCapturer: audio.AudioCapturer; // It will be called globally. + + async initAudioCapturer(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + let audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0. + } + + let audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + this.audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + console.log('AudioRecLog: Create audio capturer success.'); + } - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - let audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0. - } - - let audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - console.log('AudioRecLog: Create audio capturer success.'); ``` 2. Use **start()** to start audio recording. @@ -60,23 +71,18 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. ```js - import audio from '@ohos.multimedia.audio'; - - async function startCapturer() { - let state = audioCapturer.state; + async startCapturer() { + let state = this.audioCapturer.state; // The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Capturer is not in a correct state to start'); - return; - } - await audioCapturer.start(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.error('AudioRecLog: Capturer start failed'); + if (state == audio.AudioState.STATE_PREPARED || state == audio.AudioState.STATE_PAUSED || + state == audio.AudioState.STATE_STOPPED) { + await this.audioCapturer.start(); + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.error('AudioRecLog: Capturer start failed'); + } } } ``` @@ -86,91 +92,88 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference The following example shows how to write recorded data into a file. ```js - import fs from '@ohos.file.fs'; - - let state = audioCapturer.state; - // The read operation can be performed only when the state is STATE_RUNNING. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Capturer is not in a correct state to read'); - return; - } - - const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. - let file = fs.openSync(filePath, 0o2); - let fd = file.fd; - if (file !== null) { - console.info('AudioRecLog: file created'); - } else { - console.info('AudioRecLog: file create : FAILED'); - return; - } - - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - let numBuffersToCapture = 150; // Write data for 150 times. - let count = 0; - while (numBuffersToCapture) { - let bufferSize = await audioCapturer.getBufferSize(); - let buffer = await audioCapturer.read(bufferSize, true); - let options = { - offset: count * this.bufferSize, - length: this.bufferSize + async readData(){ + let state = this.audioCapturer.state; + // The read operation can be performed only when the state is STATE_RUNNING. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Capturer is not in a correct state to read'); + return; } - if (typeof(buffer) == undefined) { - console.info('AudioRecLog: read buffer failed'); + const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. + let file = fs.openSync(path, 0o2); + let fd = file.fd; + if (file !== null) { + console.info('AudioRecLog: file created'); } else { - let number = fs.writeSync(fd, buffer, options); - console.info(`AudioRecLog: data written: ${number}`); - } - numBuffersToCapture--; - count++; + console.info('AudioRecLog: file create : FAILED'); + return; + } + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + let numBuffersToCapture = 150; // Write data for 150 times. + let count = 0; + while (numBuffersToCapture) { + this.bufferSize = await this.audioCapturer.getBufferSize(); + let buffer = await this.audioCapturer.read(this.bufferSize, true); + let options = { + offset: count * this.bufferSize, + length: this.bufferSize + } + if (typeof(buffer) == undefined) { + console.info('AudioRecLog: read buffer failed'); + } else { + let number = fs.writeSync(fd, buffer, options); + console.info(`AudioRecLog: data written: ${number}`); + } + numBuffersToCapture--; + count++; + } } ``` 4. Once the recording is complete, call **stop()** to stop the recording. ```js - async function StopCapturer() { - let state = audioCapturer.state; - // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. - if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { - console.info('AudioRecLog: Capturer is not running or paused'); - return; - } - - await audioCapturer.stop(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.error('AudioRecLog: Capturer stop failed'); - } - } + async StopCapturer() { + let state = this.audioCapturer.state; + // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('AudioRecLog: Capturer is not running or paused'); + return; + } + + await this.audioCapturer.stop(); + + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.error('AudioRecLog: Capturer stop failed'); + } + } ``` 5. After the task is complete, call **release()** to release related resources. ```js - async function releaseCapturer() { - let state = audioCapturer.state; - // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('AudioRecLog: Capturer already released'); - return; - } - - await audioCapturer.release(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } - } + async releaseCapturer() { + let state = this.audioCapturer.state; + // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('AudioRecLog: Capturer already released'); + return; + } + + await this.audioCapturer.release(); + + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + } ``` 6. (Optional) Obtain the audio capturer information. @@ -178,23 +181,20 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference You can use the following code to obtain the audio capturer information: ```js - // Obtain the audio capturer state. - let state = audioCapturer.state; - - // Obtain the audio capturer information. - let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); - - // Obtain the audio stream information. - let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); - - // Obtain the audio stream ID. - let audioStreamId : number = await audioCapturer.getAudioStreamId(); - - // Obtain the Unix timestamp, in nanoseconds. - let audioTime : number = await audioCapturer.getAudioTime(); - - // Obtain a proper minimum buffer size. - let bufferSize : number = await audioCapturer.getBufferSize(); + async getAudioCapturerInfo(){ + // Obtain the audio capturer state. + let state = this.audioCapturer.state; + // Obtain the audio capturer information. + let audioCapturerInfo : audio.AudioCapturerInfo = await this.audioCapturer.getCapturerInfo(); + // Obtain the audio stream information. + let audioStreamInfo : audio.AudioStreamInfo = await this.audioCapturer.getStreamInfo(); + // Obtain the audio stream ID. + let audioStreamId : number = await this.audioCapturer.getAudioStreamId(); + // Obtain the Unix timestamp, in nanoseconds. + let audioTime : number = await this.audioCapturer.getAudioTime(); + // Obtain a proper minimum buffer size. + let bufferSize : number = await this.audioCapturer.getBufferSize(); + } ``` 7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. @@ -202,12 +202,13 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. ```js - audioCapturer.on('markReach', (reachNumber) => { - console.info('Mark reach event Received'); - console.info(`The Capturer reached frame: ${reachNumber}`); - }); - - audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + async markReach(){ + this.audioCapturer.on('markReach', 10, (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The Capturer reached frame: ${reachNumber}`); + }); + this.audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + } ``` 8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. @@ -215,40 +216,43 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. ```js - audioCapturer.on('periodReach', (reachNumber) => { - console.info('Period reach event Received'); - console.info(`In this period, the Capturer reached frame: ${reachNumber}`); - }); - - audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + async periodReach(){ + this.audioCapturer.on('periodReach', 10, (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the Capturer reached frame: ${reachNumber}`); + }); + this.audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + } ``` 9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type. ```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; - } - }); + async stateChange(){ + this.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; + } + }); + } ``` diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index 4a39544e7483b68d0bc15b00d643c8403dbded46..0a58ea5251744162d9948c23e75351b298a95bb8 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -19,61 +19,68 @@ The following figure shows the audio renderer state transitions. ![audio-renderer-state](figures/audio-renderer-state.png) - **PREPARED**: The audio renderer enters this state by calling **create()**. - - **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. - - **PAUSED**: The audio renderer enters this state by calling **pause()** when it is in the **RUNNING** state. When the audio playback is paused, it can call **start()** to resume the playback. - - **STOPPED**: The audio renderer enters this state by calling **stop()** when it is in the **PAUSED** or **RUNNING** state. - - **RELEASED**: The audio renderer enters this state by calling **release()** when it is in the **PREPARED**, **PAUSED**, or **STOPPED** state. In this state, the audio renderer releases all occupied hardware and software resources and will not transit to any other state. ## How to Develop For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). -1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. - +1. Use **createAudioRenderer()** to create a global **AudioRenderer** instance. Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. ```js - import audio from '@ohos.multimedia.audio'; - + import audio from '@ohos.multimedia.audio'; + import fs from '@ohos.file.fs'; + + // Perform a self-test on APIs related to audio rendering. + @Entry + @Component + struct AudioRenderer1129 { + private audioRenderer: audio.AudioRenderer; + private bufferSize; // It will be used for the call of the write function in step 3. + private audioRenderer1: audio.AudioRenderer; // It will be used for the call in the complete example in step 14. + private audioRenderer2: audio.AudioRenderer; // It will be used for the call in the complete example in step 14. + + async initAudioRender(){ let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } let audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. } let audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + this.audioRenderer = await audio.createAudioRenderer(audioRendererOptions); console.log("Create audio renderer success."); + } + } ``` 2. Use **start()** to start audio rendering. - + ```js - async function startRenderer() { - let state = audioRenderer.state; + async startRenderer() { + let state = this.audioRenderer.state; // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state when start() is called. if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && - state != audio.AudioState.STATE_STOPPED) { + state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - await audioRenderer.start(); + await this.audioRenderer.start(); - state = audioRenderer.state; + state = this.audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); } else { @@ -81,116 +88,102 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference } } ``` + The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. - - + 3. Call **write()** to write data to the buffer. - Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. + Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. Import fs from '@ohos.file.fs'; as step 1. ```js - import fs from '@ohos.file.fs'; - import audio from '@ohos.multimedia.audio'; - - async function writeBuffer(buf) { - // The write operation can be performed only when the state is STATE_RUNNING. - if (audioRenderer.state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - 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'); - } - } + async writeData(){ + // Set a proper buffer size for the audio renderer. You can also select a buffer of another size. + this.bufferSize = await this.audioRenderer.getBufferSize(); + let dir = globalThis.fileDir; // You must use the sandbox path. + const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav + console.info(`file filePath: ${ filePath}`); - // Set a proper buffer size for the audio renderer. You can also select a buffer of another size. - const bufferSize = await audioRenderer.getBufferSize(); - let dir = globalThis.fileDir; // You must use the sandbox path. - const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav - console.info(`file filePath: ${ filePath}`); - - let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); - let stat = await fs.stat(filePath); // Music file information. - let buf = new ArrayBuffer(bufferSize); - let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - for (let i = 0;i < len; i++) { - let options = { - offset: i * this.bufferSize, - length: this.bufferSize - } - let readsize = await fs.read(file.fd, buf, options) - let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer.write(buf,(err,writeSize)=>{ - if(err){ - reject(err) - }else{ - resolve(writeSize) - } + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + let stat = await fs.stat(filePath); // Music file information. + let buf = new ArrayBuffer(this.bufferSize); + let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); + for (let i = 0;i < len; i++) { + let options = { + offset: i * this.bufferSize, + length: this.bufferSize + } + let readsize = await fs.read(file.fd, buf, options) + let writeSize = await new Promise((resolve,reject)=>{ + this.audioRenderer.write(buf,(err,writeSize)=>{ + if(err){ + reject(err) + }else{ + resolve(writeSize) + } + }) }) - }) + } + + fs.close(file) + await this.audioRenderer.stop(); // Stop rendering. + await this.audioRenderer.release(); // Release the resources. } - - fs.close(file) - await audioRenderer.stop(); // Stop rendering. - await audioRenderer.release(); // Releases the resources. ``` 4. (Optional) Call **pause()** or **stop()** to pause or stop rendering. ```js - async function pauseRenderer() { - let state = audioRenderer.state; - // The audio renderer can be paused only when it is in the STATE_RUNNING 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() { - let state = audioRenderer.state; - // The audio renderer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED 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 pauseRenderer() { + let state = this.audioRenderer.state; + // The audio renderer can be paused only when it is in the STATE_RUNNING state. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await this.audioRenderer.pause(); + + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async stopRenderer() { + let state = this.audioRenderer.state; + // The audio renderer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await this.audioRenderer.stop(); + + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } ``` 5. (Optional) Call **drain()** to clear the buffer. ```js - async function drainRenderer() { - let state = audioRenderer.state; - // drain() can be used only when the audio renderer is in the STATE_RUNNING state. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.drain(); - state = audioRenderer.state; + async drainRenderer() { + let state = this.audioRenderer.state; + // drain() can be used only when the audio renderer is in the STATE_RUNNING state. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; } + + await this.audioRenderer.drain(); + state = this.audioRenderer.state; + } ``` 6. After the task is complete, call **release()** to release related resources. @@ -198,67 +191,63 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. ```js - async function releaseRenderer() { - let state = audioRenderer.state; - // The audio renderer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('Renderer already released'); - return; - } - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } + async releaseRenderer() { + let state = this.audioRenderer.state; + // The audio renderer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('Renderer already released'); + return; + } + await this.audioRenderer.release(); + + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } } ``` 7. (Optional) Obtain the audio renderer information. - + You can use the following code to obtain the audio renderer information: ```js - // Obtain the audio renderer state. - let state = audioRenderer.state; - - // Obtain the audio renderer information. - let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo(); - - // Obtain the audio stream information. - let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo(); - - // Obtain the audio stream ID. - let audioStreamId : number = await audioRenderer.getAudioStreamId(); - - // Obtain the Unix timestamp, in nanoseconds. - let audioTime : number = await audioRenderer.getAudioTime(); - - // Obtain a proper minimum buffer size. - let bufferSize : number = await audioRenderer.getBufferSize(); - - // Obtain the audio renderer rate. - let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); + async getRenderInfo(){ + // Obtain the audio renderer state. + let state = this.audioRenderer.state; + // Obtain the audio renderer information. + let audioRendererInfo : audio.AudioRendererInfo = await this.audioRenderer.getRendererInfo(); + // Obtain the audio stream information. + let audioStreamInfo : audio.AudioStreamInfo = await this.audioRenderer.getStreamInfo(); + // Obtain the audio stream ID. + let audioStreamId : number = await this.audioRenderer.getAudioStreamId(); + // Obtain the Unix timestamp, in nanoseconds. + let audioTime : number = await this.audioRenderer.getAudioTime(); + // Obtain a proper minimum buffer size. + let bufferSize : number = await this.audioRenderer.getBufferSize(); + // Obtain the audio renderer rate. + let renderRate : audio.AudioRendererRate = await this.audioRenderer.getRenderRate(); + } ``` 8. (Optional) Set the audio renderer information. - + You can use the following code to set the audio renderer information: ```js - // Set the audio renderer rate to RENDER_RATE_NORMAL. - let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; - await audioRenderer.setRenderRate(renderRate); - - // Set the interruption mode of the audio renderer to SHARE_MODE. - let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; - await audioRenderer.setInterruptMode(interruptMode); - - // Set the volume of the stream to 0.5. - let volume : number = 0.5; - await audioRenderer.setVolume(volume); + async setAudioRenderInfo(){ + // Set the audio renderer rate to RENDER_RATE_NORMAL. + let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; + await this.audioRenderer.setRenderRate(renderRate); + // Set the interruption mode of the audio renderer to SHARE_MODE. + let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; + await this.audioRenderer.setInterruptMode(interruptMode); + // Set the volume of the stream to 0.5. + let volume : number = 0.5; + await this.audioRenderer.setVolume(volume); + } ``` 9. (Optional) Use **on('audioInterrupt')** to subscribe to the audio interruption event, and use **off('audioInterrupt')** to unsubscribe from the event. @@ -270,110 +259,116 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption-unaware applications can use **audioRenderer.state** to check the audio renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). It should be noted that the audio interruption event subscription of the **AudioRenderer** module is slightly different from **on('interrupt')** in [AudioManager](../reference/apis/js-apis-audio.md#audiomanager). The **on('interrupt')** and **off('interrupt')** APIs are deprecated since API version 9. In the **AudioRenderer** module, you only need to call **on('audioInterrupt')** to listen for focus change events. When the **AudioRenderer** instance created by the application performs actions such as start, stop, and pause, it requests the focus, which triggers focus transfer and in return enables the related **AudioRenderer** instance to receive a notification through the callback. For instances other than **AudioRenderer**, such as frequency modulation (FM) and voice wakeup, the application does not create an instance. In this case, the application can call **on('interrupt')** in **AudioManager** to receive a focus change notification. - + ```js - audioRenderer.on('audioInterrupt', (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) { + async subscribeAudioRender(){ + this.audioRenderer.on('audioInterrupt', (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) { // Forcible pausing initiated by the audio framework. To prevent data loss, stop the write operation. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('isPlay is false'); + break; // Forcible stopping initiated by the audio framework. To prevent data loss, stop the write operation. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('isPlay is false'); + break; // Forcible ducking initiated by the audio framework. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; // Undocking initiated by the audio framework. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { // Notify the application that the rendering starts. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + this.startRenderer(); + break; // Notify the application that the audio stream is interrupted. The application then determines whether to continue. (In this example, the application pauses the rendering.) - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('isPlay is false'); + this.pauseRenderer(); + break; + } } - } - }); - - audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be listened for. + }); + } ``` 10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. After the mark reached event is subscribed to, when the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - audioRenderer.on('markReach', (reachNumber) => { - console.info('Mark reach event Received'); - console.info(`The renderer reached frame: ${reachNumber}`); - }); - audioRenderer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + ```js + async markReach(){ + this.audioRenderer.on('markReach', 50, (position) => { + if (position == 50) { + console.info('ON Triggered successfully'); + } + }); + this.audioRenderer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + } ``` 11. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. After the period reached event is subscribed to, each time the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - audioRenderer.on('periodReach', (reachNumber) => { - console.info('Period reach event Received'); - console.info(`In this period, the renderer reached frame: ${reachNumber} `); - }); - audioRenderer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + ```js + async periodReach(){ + this.audioRenderer.on('periodReach',10, (reachNumber) => { + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); + + this.audioRenderer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + } ``` 12. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. After the **stateChange** event is subscribed to, when the audio renderer state changes, a callback is triggered and the audio renderer state is returned. - + ```js - audioRenderer.on('stateChange', (audioState) => { - console.info('State change event Received'); - console.info(`Current renderer state is: ${audioState}`); - }); + async stateChange(){ + this.audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + } ``` 13. (Optional) Handle exceptions of **on()**. If the string or the parameter type passed in **on()** is incorrect , the application throws an exception. In this case, you can use **try catch** to capture the exception. - + ```js - try { - audioRenderer.on('invalidInput', () => { // The string is invalid. - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // The application throws exception 401. - } - try { - audioRenderer.on(1, () => { // The type of the input parameter is incorrect. - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // The application throws exception 6800101. + async errorCall(){ + try { + this.audioRenderer.on('invalidInput', () => { // The string is invalid. + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // The application throws exception 401. + } + try { + this.audioRenderer.on(1, () => { // The type of the input parameter is incorrect. + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // The application throws exception 6800101. + } } ``` 14. (Optional) Refer to the complete example of **on('audioInterrupt')**. - - Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. - - ```js + Declare audioRenderer1 and audioRenderer2 first. For details, see step 1. + Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. + ```js async runningAudioRender1(){ let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, @@ -388,33 +383,33 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference } let audioRendererOptions = { streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + rendererInfo: audioRendererInfo } - + // 1.1 Create an instance. - audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); + this.audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); console.info("Create audio renderer 1 success."); - + // 1.2 Set the independent mode. - audioRenderer1.setInterruptMode(1).then( data => { + this.audioRenderer1.setInterruptMode(1).then( data => { console.info('audioRenderer1 setInterruptMode Success!'); }).catch((err) => { - console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); + console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); }); - + // 1.3 Set the listener. - audioRenderer1.on('audioInterrupt', async(interruptEvent) => { - console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + this.audioRenderer1.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) }); - + // 1.4 Start rendering. - await audioRenderer1.start(); + await this.audioRenderer1.start(); console.info('startAudioRender1 success'); - + // 1.5 Obtain the buffer size, which is the proper minimum buffer size of the audio renderer. You can also select a buffer of another size. - const bufferSize = await audioRenderer1.getBufferSize(); + const bufferSize = await this.audioRenderer1.getBufferSize(); console.info(`audio bufferSize: ${bufferSize}`); - + // 1.6 Obtain the original audio data file. let dir = globalThis.fileDir; // You must use the sandbox path. const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav @@ -423,14 +418,14 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference let stat = await fs.stat(path1); // Music file information. let buf = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - + // 1.7 Render the original audio data in the buffer by using audioRender. for (let i = 0;i < len; i++) { let options = { offset: i * this.bufferSize, length: this.bufferSize } - let readsize = await fs.read(file.fd, buf, options) + let readsize = await fs.read(file1.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ this.audioRenderer1.write(buf,(err,writeSize)=>{ if(err){ @@ -439,13 +434,13 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference resolve(writeSize) } }) - }) + }) } fs.close(file1) - await audioRenderer1.stop(); // Stop rendering. - await audioRenderer1.release(); Releases the resources. + await this.audioRenderer1.stop(); // Stop rendering. + await this.audioRenderer1.release(); // Release the resources. } - + async runningAudioRender2(){ let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, @@ -460,33 +455,33 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference } let audioRendererOptions = { streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + rendererInfo: audioRendererInfo } - + // 2.1 Create another instance. - audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); + this.audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); console.info("Create audio renderer 2 success."); - + // 2.2 Set the independent mode. - audioRenderer2.setInterruptMode(1).then( data => { + this.audioRenderer2.setInterruptMode(1).then( data => { console.info('audioRenderer2 setInterruptMode Success!'); }).catch((err) => { - console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); + console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); }); - + // 2.3 Set the listener. - audioRenderer2.on('audioInterrupt', async(interruptEvent) => { - console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + this.audioRenderer2.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) }); - + // 2.4 Start rendering. - await audioRenderer2.start(); + await this.audioRenderer2.start(); console.info('startAudioRender2 success'); - + // 2.5 Obtain the buffer size. - const bufferSize = await audioRenderer2.getBufferSize(); + const bufferSize = await this.audioRenderer2.getBufferSize(); console.info(`audio bufferSize: ${bufferSize}`); - + // 2.6 Read the original audio data file. let dir = globalThis.fileDir; // You must use the sandbox path. const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav @@ -495,14 +490,14 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference let stat = await fs.stat(path2); // Music file information. let buf = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - + // 2.7 Render the original audio data in the buffer by using audioRender. for (let i = 0;i < len; i++) { let options = { offset: i * this.bufferSize, length: this.bufferSize } - let readsize = await fs.read(file.fd, buf, options) + let readsize = await fs.read(file2.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ this.audioRenderer2.write(buf,(err,writeSize)=>{ if(err){ @@ -511,28 +506,17 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference resolve(writeSize) } }) - }) + }) } fs.close(file2) - await audioRenderer2.stop(); // Stop rendering. - await audioRenderer2.release(); // Releases the resources. + await this.audioRenderer2.stop(); // Stop rendering. + await this.audioRenderer2.release(); // Release the resources. } - - async writeBuffer(buf, audioRender) { - let writtenbytes; - await audioRender.write(buf).then((value) => { - writtenbytes = value; - console.info(`Actual written bytes: ${writtenbytes} `); - }); - if (typeof(writtenbytes) != 'number' || writtenbytes < 0) { - console.error('get Write buffer failed. check the state of renderer'); - } - } - + // Integrated invoking entry. async test(){ - await runningAudioRender1(); - await runningAudioRender2(); + await this.runningAudioRender1(); + await this.runningAudioRender2(); } - - ``` + + ``` \ No newline at end of file diff --git a/en/application-dev/media/avplayer-playback.md b/en/application-dev/media/avplayer-playback.md index 324dd43e6f73d46e5f0d264ae81ba36802ee6021..9a7d9ffa10e2de83e676adbd2c5af7f9b3ba35af 100644 --- a/en/application-dev/media/avplayer-playback.md +++ b/en/application-dev/media/avplayer-playback.md @@ -292,13 +292,13 @@ export class AVPlayerDemo { async avPlayerDemo() { // Create an AVPlayer instance. this.avPlayer = await media.createAVPlayer() - let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. - let path = pathDir + '/H264_AAC.mp4' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - this.avPlayer.url = fdPath + let fileDescriptor = undefined + // Use getRawFileDescriptor of the resource management module to obtain the media assets in the application, and use the fdSrc attribute of the AVPlayer to initialize the media assets. + // For details on the fd/offset/length parameter, see the Media API. The globalThis.abilityContext parameter is a system environment variable and is saved as a global variable on the main page during the system boost. + await globalThis.abilityContext.resourceManager.getRawFileDescriptor('H264_AAC.mp4').then((value) => { + fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length} + }) + this.avPlayer.fdSrc = fileDescriptor } } ``` diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md index bf85581053f30d6aa56e0218c51339ef6ee3f268..55070f9e38666be2c6cd5cf87b3d3680df0293ba 100644 --- a/en/application-dev/notification/Readme-EN.md +++ b/en/application-dev/notification/Readme-EN.md @@ -1,7 +1,7 @@ # Notification - [Notification Overview](notification-overview.md) -- [Notification Subscription (Open Only to System Applications)](notification-subscription.md) +- [Notification Subscription (for System Applications)](notification-subscription.md) - [Enabling Notification](notification-enable.md) - Publishing a Notification - [Publishing a Basic Notification](text-notification.md) diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md index c62b65a25c4d80b37610449e6309e05ef259893f..95fe77de7feead97208082c12519523588cd6521 100644 --- a/en/application-dev/notification/notification-subscription.md +++ b/en/application-dev/notification/notification-subscription.md @@ -1,4 +1,4 @@ -# Notification Subscription (Open Only to System Applications) +# Notification Subscription (for System Applications Only) To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application. diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md index d79f09578a0dc58b0aa53e45b68264f85e67e2c2..8090e7e835dae7f0658127fafbf04680a4e81114 100644 --- a/en/application-dev/notification/progress-bar-notification.md +++ b/en/application-dev/notification/progress-bar-notification.md @@ -27,7 +27,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n ```ts notificationManager.isSupportTemplate('downloadTemplate').then((data) => { console.info(`[ANS] isSupportTemplate success`); - let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. + let isSupportTpl: boolean = data; // The value true means that the template of the downloadTemplate type is supported, and false means the opposite. // ... }).catch((err) => { console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md index a9d9bdaaaccc731f0e7cec7e3f7a7e74a3aa41d6..7901a78a4c547ca02caae191b551d27f6cae3e3a 100644 --- a/en/application-dev/notification/text-notification.md +++ b/en/application-dev/notification/text-notification.md @@ -127,10 +127,10 @@ The following table describes the APIs for notification publishing. You specify Below is an example of the multi-line notification. ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png) - - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB. + - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) object that does not exceed 2 MB. ```ts - let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. + let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { @@ -141,7 +141,7 @@ The following table describes the APIs for notification publishing. You specify additionalText: 'test_additionalText', briefText: 'test_briefText', expandedTitle: 'test_expandedTitle', - picture: notificationPicture + picture: imagePixelMap } } } diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 439bbdcb9d9455a36c75ceb8ba39e728d1aecebd..e0350b4c4ab31285f37eb18e819a4e84ad0759a7 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -10,7 +10,6 @@ - Application Package Structure - [Application Package Structure in Stage Model](application-package-structure-stage.md) - [Application Package Structure in FA Model](application-package-structure-fa.md) - - [HAR File Structure](har-structure.md) - Multi-HAP Mechanism - [Multi-HAP Design Objectives](multi-hap-objective.md) - [Multi-HAP Build View](multi-hap-build-view.md) diff --git a/en/application-dev/quick-start/application-package-update.md b/en/application-dev/quick-start/application-package-update.md new file mode 100644 index 0000000000000000000000000000000000000000..0137bc47e7ad78345da1128cf423e445d8456f97 --- /dev/null +++ b/en/application-dev/quick-start/application-package-update.md @@ -0,0 +1,5 @@ +# Application Package Update Process +The OpenHarmony bundle manager service allows application packages to be updated under the following scenarios: + +1. In the application market: The application market notifies the user of an available update, and the user can install the update by following the onscreen instructions. +2. In the application: When the application for which an update is available starts up, the application market notifies the user of the update, and the user can install the update by following the onscreen instructions. diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md index 0cb38c2c123171b7ebe05df263b7275445542986..c59ee04dccef3411c25326851c446dcdd3f7164f 100644 --- a/en/application-dev/quick-start/arkts-rendering-control.md +++ b/en/application-dev/quick-start/arkts-rendering-control.md @@ -42,6 +42,8 @@ ForEach( ) ``` +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory| Description | diff --git a/en/application-dev/quick-start/figures/quick-fix-debug.png b/en/application-dev/quick-start/figures/quick-fix-debug.png new file mode 100644 index 0000000000000000000000000000000000000000..4e7084f30e2d2b26be811c8b8a6c9ec34a005c9e Binary files /dev/null and b/en/application-dev/quick-start/figures/quick-fix-debug.png differ diff --git a/en/application-dev/quick-start/figures/quick-fix-devel_release.png b/en/application-dev/quick-start/figures/quick-fix-devel_release.png new file mode 100644 index 0000000000000000000000000000000000000000..34b701fafe5d319da6b552c5d86305151e8e28b3 Binary files /dev/null and b/en/application-dev/quick-start/figures/quick-fix-devel_release.png differ diff --git a/en/application-dev/quick-start/figures/quick_fix_bundle_struct.png b/en/application-dev/quick-start/figures/quick_fix_bundle_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..730414e3ba2fccbb58a27f83ce1afc572544f366 Binary files /dev/null and b/en/application-dev/quick-start/figures/quick_fix_bundle_struct.png differ diff --git a/en/application-dev/quick-start/figures/quick_fix_gen_abc.png b/en/application-dev/quick-start/figures/quick_fix_gen_abc.png new file mode 100644 index 0000000000000000000000000000000000000000..3e549ec79cad4a76a55ccab4dbb769b756d9936a Binary files /dev/null and b/en/application-dev/quick-start/figures/quick_fix_gen_abc.png differ diff --git a/en/application-dev/quick-start/figures/quick_fix_gen_so.png b/en/application-dev/quick-start/figures/quick_fix_gen_so.png new file mode 100644 index 0000000000000000000000000000000000000000..31717ca38c7e64983b9b3c95672fe966decf6945 Binary files /dev/null and b/en/application-dev/quick-start/figures/quick_fix_gen_so.png differ diff --git a/en/application-dev/quick-start/full-sdk-compile-guide.md b/en/application-dev/quick-start/full-sdk-compile-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d706c76afd647d0e96c039175f0682ed203c78b2 --- /dev/null +++ b/en/application-dev/quick-start/full-sdk-compile-guide.md @@ -0,0 +1,29 @@ +# Full SDK Compilation Guide + +The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can leverage this SDK to develop applications. + +Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. If necessary, you can compile the SDK using the full source code. + +## Compiling the Full SDK + +**Preparation** + +1. Register an SSH public key for access to Gitee. +2. Configure the server environment. For details, see [Setting Up the Ubuntu Environment](../../device-dev/quick-start/quickstart-ide-env-ubuntu.md). + +**Procedure** + +1. Download and initialize the manifest repository: **repo init -u https://gitee.com/openharmony/manifest.git -b $manifest_branch --no-repo-verify --repo-url=https://gitee.com/oschina/repo --no-clone-bundle** + +2. Download source code based on the downloaded manifest repository: **repo sync -c -d --force-sync** + +3. Perform precompilation: **yes y | apt install libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev && rm -rf prebuilts/clang/ohos/darwin-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/windows-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/linux-x86_64/clang-480513 && bash build/prebuilts_download.sh -ndk && apt-get update -qqy && apt-get install doxygen -y --force-yes** + +4. Perform compilation: **./build.sh --product-name ohos-sdk** + + +If the compilation is successful, export the files in the **out/sdk/packages/ohos-sdk/** directory. + +## Replacing the SDK + +After the full SDK is compiled, switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md). diff --git a/en/application-dev/quick-start/har-structure.md b/en/application-dev/quick-start/har-structure.md deleted file mode 100644 index 1d479b504a48752fdcb4ff033e81103efa134da2..0000000000000000000000000000000000000000 --- a/en/application-dev/quick-start/har-structure.md +++ /dev/null @@ -1,10 +0,0 @@ -# HAR File Structure - - -The OpenHarmony Archive (HAR) file enables code to be shared among multiple modules or projects. Unlike a Harmony Ability Package (HAP) file, a HAR file cannot be independently installed on a device. Instead, it can only be referenced as the dependency of an application module. - - -A HAR file is the build product of a [module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) of the Library type in a DevEco Studio project. - - -As a static shared package in OpenHarmony, the [HAR file](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) can contain the source code, C++ libraries, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model). diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 67361fccfd749495e2f5825d5ccac6efe1505ed9..2f308d7e5936d4fd62fbf5c22cee827e7bbc38a4 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -72,7 +72,7 @@ As shown above, the **module.json5** file contains several tags. | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. Chinese characters are not allowed.| String| No| -| type | Type of the module. The value can be **entry** or **feature**.
- **entry**: main module of the application.
- **feature**: dynamic feature module of the application.| String| No| +| type | Type of the module. The options are as follows:
- **entry**: main module of the application.
- **feature**: dynamic feature module of the application.
- **har**: static shared module.
- **shared**: dynamic shared module.| String| No| | srcEntry | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)| | description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)| | process | Process name of the current module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility components of the application run in the specified process.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)| @@ -150,7 +150,7 @@ Define the **main_pages.json** file under **resources/base/profile** in the deve The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**. - **Table 3** metadata +**Table 3** metadata | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -210,9 +210,10 @@ Touching this icon will direct the user to the application details screen in **S To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). + **Setting the application icon to be displayed on the home screen**: -Set **icon**, **label**, and **skills** under **abilities** in the **module.json5** file. In addition, the **skills** configuration must contain **ohos.want.action.home **and **entity.system.home**. +Set **icon**, **label**, and **skills** under **abilities** in the **module.json5** file. In addition, make sure the **skills** configuration contains **ohos.want.action.home** and **entity.system.home**. ``` { @@ -284,7 +285,7 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json | removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed.
- **true**: Remove the relevant task from the task list after the UIAbility component is destroyed.
- **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)| | orientation | Orientation of the UIAbility component when it is started. The options are as follows:
- **unspecified**: automatically determined by the system.
- **landscape**: landscape mode.
- **portrait**: portrait mode.
- **landscape_inverted**: inverted landscape mode.
- **portrait_inverted**: inverted portrait mode.
- **auto_rotation**: determined by the sensor.
- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.
- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.
- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.
- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.
- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.
- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)| | supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:
- **fullscreen**: full-screen mode.
- **split**: split-screen mode.
- **floating**: floating window mode.| String array| Yes (initial value:
["fullscreen", "split", "floating"])| -| priority | Priority of the UIAbility component. This attribute applies only to system applications and does not take effect for third-party applications. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.| Number| Yes (initial value: **0**)| +| priority | Priority of the UIAbility component. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| Number| Yes (initial value: **0**)| | maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)| | minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)| | maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowWidth** or greater than the maximum window width allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window width supported by the platform)| @@ -396,22 +397,22 @@ Example of the **skills** structure: } ``` -**Enhance implicit query** +**Enhanced implicit query** URI-level prefix matching is supported. -When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if the URI prefixed with the configuration file is passed in. +When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if a URI prefixed with the configuration file is passed in. * The query enhancement involves the following APIs: [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)
- 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
- 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
- 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>; + 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
+ 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
+ 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>; * Configuration requirements
abilities -> skills -> uris object
Configuration 1: only **scheme = 'http'**
- Configuration 2: only **(scheme = 'http' ) + ( host = 'example.com')**
- Configuration 3: only **(scheme = 'http' ) + ( host = 'example.com' ) + ( port = '8080')**
+ Configuration 2: only **(scheme = 'http') + (host = 'example.com')**
+ Configuration 3: only **(scheme = 'http') + (host = 'example.com') + (port = '8080')** * Prefix match
If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API: 1. uri = 'https://': No matches
@@ -429,8 +430,6 @@ When only **scheme** or a combination of **scheme** and **host** or **scheme**, 13. uri = 'http://example.com:9180/path': Matches configuration 1 and configuration 2
14. uri = 'http://example.com:8080/path': Matches configuration 1, configuration 2, and configuration 3
- - ## extensionAbilities The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility. @@ -446,8 +445,8 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie | label | Name of the ExtensionAbility component displayed to users. The value is a string resource index.
**NOTE**
If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No| | type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | permissions | Permissions required for another application to access the ExtensionAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission 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 ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when **type** of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| -|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application,
but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| +| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the **ExtensionAbility** component is set to **dataShare**. | String| Yes (initial value: left empty)| +|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| @@ -540,7 +539,7 @@ The **shortcut** information is identified in **metadata**, where: | 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 label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | icon | Icon of the shortcut. The value is an icon resource index.| String| Yes (initial value: left empty)| -| [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut. The value is a string.
**abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)| +| [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.
- **bundleName**: target bundle name of the shortcut. The value is a string.
- **abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)| 1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**. @@ -699,7 +698,7 @@ Configure **metadata** in the **module** tag in the **module.json5** file. The **testRunner** tag represents the supported test runner. - **Table 14** testRunner +**Table 14** testRunner | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md index e4aee36db107109fcaa7e6d068cbc907009c69d4..352a993d5042116105ef5c50ae9138df51c622c9 100644 --- a/en/application-dev/quick-start/module-structure.md +++ b/en/application-dev/quick-start/module-structure.md @@ -21,7 +21,7 @@ The **module** tag contains the HAP configuration. | reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| | colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| | distroFilter | 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 the application market 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.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| -|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the subscribed common events. When a subscribed event is sent, the static subscriber is started. Unlike the common dynamic subscriber, the static subscriber does not need to actively call the common event subscription API in the service code, and may not be started when the common event is released. In constrast, the dynamic subscriber actively calls the common event subscription API and therefore requires the application to stay active.| Object array| Yes (initial value: left empty)| +|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| 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.| Object| Yes (initial value: left empty)| @@ -190,12 +190,73 @@ Example of the metadata attribute: ## Internal Structure of the abilities Attribute +**By default, application icons cannot be hidden from the home screen in OpenHarmony.** + +The OpenHarmony system imposes a strict rule on the presence of application icons. If no icon is configured in the HAP file of an application, the system creates a default icon for the application and displays it on the home screen.
+Touching this icon will direct the user to the application details screen in **Settings**. +To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). + + +**Setting the application icon to be displayed on the home screen**:
Set **icon**, **label**, and **skills** under **abilities** in the **config.json** file. In addition, make sure the **skills** configuration contains **ohos.want.action.home** and **entity.system.home**. +``` +{ + "module":{ + + ... + + "abilities": [{ + "icon": "$media:icon", + "label": "Login", + "skills": [{ + "actions": ["ohos.want.action.home"], + "entities": ["entity.system.home"], + "uris": [] + }] + }], + + ... + + } +} +``` + +**Querying an application icon:** +* The HAP file contains Page ability configuration. + * The application icon is set under **abilities** in the **config.json** file. + * The application does not have the privilege to hide its icon from the home screen. + * The returned home screen icon is the icon configured for the ability. + * The returned home screen label is the label configured for the ability. If no label is configured, the bundle name is returned. + * The returned component name is the component name of the ability. + * When the user touches the home screen icon, the home screen of the ability is displayed. + * The application has the privilege to hide its icon from the home screen. + * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. + * The application icon is not set under **abilities** in the **config.json** file. + * The application does not have the privilege to hide its icon from the home screen. + * The returned home screen icon is the default icon. + *The returned home screen label is the bundle name of the application. + * The returned component name is the component name displayed on the application details screen (this component is built in the system). + * Touching the home screen icon will direct the user to the application details screen. + * The application has the privilege to hide its icon from the home screen. + * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. +* The HAP file does not contain Page ability configuration. + * The application does not have the privilege to hide its icon from the home screen. + * The returned home screen icon is the default icon. + *The returned home screen label is the bundle name of the application. + * The returned component name is the component name displayed on the application details screen (this component is built in the system). + * Touching the home screen icon will direct the user to the application details screen. + * The application has the privilege to hide its icon from the home screen. + * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. + +> **NOTE** +> +> The icon and label displayed on the application details page may be different from those displayed on the home screen. For non-Page abilities, they are the entry icon and label set under **abilities**, if any. + **Table 8** Internal structure of the abilities attribute | Name| 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. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| -| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to 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 bytes.| String| No| +| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes.| 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 bytes.| 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 displayed 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)| @@ -212,13 +273,13 @@ Example of the metadata attribute: | 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)| | writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| -| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. The options 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 selectes 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)| +| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. The options 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 selects 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.| 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.| String| Yes (initial value: left empty, indicating that the current ability is not an alias)| | formsEnabled | Whether the ability can provide widgets. This attribute applies only to the ability using the Page template.
**true**: This ability can provide widgets.
**false**: This ability cannot provide widgets.| Boolean| Yes (initial value: **false**)| | forms | Information about the widgets used by the ability. This attribute is valid only when **formsEnabled** is set to **true**.| Object array| Yes (initial value: left empty)| | srcLanguage | Programming language of the ability, which you can specify when creating the project.| String| Yes (initial value: **"js"**)| -| srcPath | JS code path corresponding to the ability. The value can contain maximum of 127 bytes.| String| No| +| srcPath | JS code path corresponding to the ability. The value can contain a maximum of 127 bytes.| String| No| | 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.| Object| 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)| @@ -351,9 +412,42 @@ Example of the **skills** attribute structure: ] ``` -## reqPermissions Attributes - -**Table 12** reqPermissions attributes +**Enhanced implicit query** + +URI-level prefix matching is supported. + +When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if a URI prefixed with the configuration file is passed in. + + * The query enhancement involves the following APIs:
+ [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)
+ 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
+ 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
+ 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>; + * Configuration requirements
+ abilities -> skills -> uris object
+ Configuration 1: only **scheme = 'http'** + Configuration 2: only **(scheme = 'http') + (host = 'www.example.com')** + Configuration 3: only **(scheme = 'http') + (host = 'www.example.com') + (port = '8080')** + * Prefix match
+ If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API:
+ 1. uri = 'https://': No matches
+ 2. uri = 'http://': Matches configuration 1
+ 3. uri = 'https://www.example.com': No matches
+ 4. uri = 'https://www.exa.com': No matches
+ 5. uri = 'http://www.exa.com': Matches configuration 1
+ 6. uri = 'http://www.example.com': Matches configuration 1 and configuration 2
+ 7. uri = 'https://www.example.com:8080': No matches
+ 8. uri = 'http://www.exampleaa.com:8080': Matches configuration 1
+ 9. uri = 'http://www.example.com:9180': Matches configuration 1 and configuration 2
+ 10. uri = 'http://www.example.com:8080': Matches configuration 1, configuration 2, and configuration 3
+ 11. uri = 'https://www.example.com:9180/query/student/name' : No matches
+ 12. uri = 'http://www.exampleap.com:8080/query/student/name': Matches configuration 1
+ 13. uri = 'http://www.example.com:9180/query/student/name': Matches configuration 1 and configuration 2
+ 14. uri = 'http://www.example.com:8080/query/student/name': Matches configuration 1, configuration 2, and configuration 3
+ +## Internal Structure of the reqPermissions Attribute + +**Table 12** Internal structure of the reqPermissions attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -687,7 +781,7 @@ Example of the **commonEvents** attribute structure: | -------- | -------- | -------- | -------- | | name | Name of a permission. The value can contain a maximum of 255 bytes.| String| No| | grantMode | Permission grant mode. The options are as follows:
- **system_grant**: The permission is automatically granted by the system after the application is installed.
- **user_grant**: The permission is dynamically requested when needed and must be granted by the user.| String| Yes (initial value: **"system_grant"**)| -| availableLevel | Permission type. The options are as follows:
- **system_core**: system core permission.
- **system_basic**: basic system permission.
- **normal**: normal permission, which can be requsted by all applications.| String| Yes (initial value: **"normal"**)| +| availableLevel | Permission type. The options are as follows:
- **system_core**: system core permission.
- **system_basic**: basic system permission.
- **normal**: normal permission, which can be requested by all applications.| String| Yes (initial value: **"normal"**)| | provisionEnable | Whether the permission can be requested in provision mode, including high-level permissions. The value **true** means that 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 to the description.| String| Yes (initial value: left empty)| diff --git a/en/application-dev/quick-start/quickfix-debug.md b/en/application-dev/quick-start/quickfix-debug.md new file mode 100644 index 0000000000000000000000000000000000000000..b7cdf872c72198e796be1f1b65e635cb52ce04e6 --- /dev/null +++ b/en/application-dev/quick-start/quickfix-debug.md @@ -0,0 +1,92 @@ +# CLI-based Quick Fix Development + +You can use the command-line tool to develop a quick fix file, an expeditious approach to resolve application bugs. In this document, an application with the bundle name of **com.ohos.quickfix** in version 1000000 is used as an example to describe how to develop a quick fix file with the command-line tool. + +## Writing the patch.json File + +Write a **patch.json** file that meets your project requirements and place it in any directory of the project. (Configuring the **patch.json** file is not supported in DevEco Studio.) Create a **patch.json** file on the local computer. Below is an example of the file content: +```json +{ + "app" : { + "bundleName" : "com.ohos.quickfix", + "versionCode": 1000000, // Application version + "versionName" : "1.0.0.1", + "patchVersionCode": 1000000, // Patch version + "patchVersionName" : "1.0.0.1" + }, + "module" : { + "name" : "entry", + "type" : "patch", + "deviceTypes" : [ + "default", + "tablet" + ], + "originalModuleHash": "11223344556677889900" // SHA-256 value of the HAP file to restore + } +} +``` + +## Generating a Quick Fix File +### Quick Fix for TS Code +* After modifying the TS code file in DevEco Studio and build it into a HAP file, you can find the corresponding .abc file in the project directory, for example, **build\default\cache\default\LegacyCompileETS\jsbundle\temporary\pages\index.abc**. + +### Quick Fix for C++ Code + +* In DevEco Studio, build the original C++ code into a .so file. Fix bugs in the code and rebuild the code into a new .so file. You can find this .so file in the project directory, for example, **build\default\intermediates\libs\default\arm64-v8a\libentry.so**. +* Locate the **diff.exe** tool in the **toolchains** folder in the local OpenHarmony SDK path. Use this tool to generate a quick fix .so file based on the old and new .so files. The command is as follows: +```shell +$ diff.exe -s Example.z.so -d Example.z.so -p Example.z.so.diff +``` +The command contains the following options: +- -**s**: path to the old .so file +- -**d**: path to the new .so file +- -**p**: path of the generated differential file + +## Generating a Quick Fix File in .hqf Format + +With the preceding **patch.json**, .abc, and .so files, run the following command to generate an .hqf file using the **app_packing_tool.jar** tool in the **toolchains** folder in the local OpenHarmony SDK path: +```shell +$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-patch patchs --out-path entry-default-unsigned.hqf --force true +``` + +The command contains the following options. +| Option|Description | Remarks| +| --- | --- |---| +| mode |Mode. | Mandatory| +| json-path|Path to the **patch.json** file.|Mandatory| +| lib-path|Path to the quick fix .so file. For details about the path, see [Structure of the Quick Fix Package](quickfix-principles.md#structure-of-the-quick-fix-package).|Optional| +| ets-path|Path to the quick fix .abc file.|Optional| + +## Signing the Quick Fix File + +Use the [hapsigner](../security/hapsigntool-guidelines.md) tool to sign the **entry-default-unsigned.hqf** file, in the same way you sign a HAP file. To be specific, run the following command to use **hap-sign-tool.jar** in the **toolchains** folder in the local OpenHarmony SDK path: + +```shell +$ java -jar hap-sign-tool.jar sign-app -keyAlias "OpenHarmony Application Release" -signAlg "SHA256withECDSA" -mode "localSign" -appCertFile "OpenHarmonyApplication.pem" -profileFile "ohos_provision_release.p7b" -inFile "entry-default-unsigned.hqf" -keystoreFile "OpenHarmony.p12" -outFile "entry-signed-release.hqf" -keyPwd "123456" -keystorePwd "123456" +``` + +## Installing the Quick Fix File + +Push the **entry-signed-release.hqf** file to the device. +```shell +hdc.exe file send .\entry-signed-release.hqf /data/ +``` + +Run the following command to install the quick fix file as a patch: +```shell +$ bm quickfix -a -f /data/entry-signed-release.hqf +``` + +The complete commands are as follows: +``` +$ bm quickfix -h +usage: bm quickfix +options list: +-h, --help list available commands +-q, --query indicates query quickfix, used with -b or --bundle-name +-b, --bundle-name query quickfix status and information by a specified bundle name +-a, --apply indicates apply quickfix, used with -f or --file-path +-f, --file-path apply a quickfix file by a specified path +-f, --file-path ... apply some quickfix files of one bundle +-f, --file-path apply quickfix files by direction, under which are quickfix files +``` diff --git a/en/application-dev/quick-start/quickfix-principles.md b/en/application-dev/quick-start/quickfix-principles.md new file mode 100644 index 0000000000000000000000000000000000000000..4c0a1f684cfc1ff71c5ad9a2594ae8823e178e82 --- /dev/null +++ b/en/application-dev/quick-start/quickfix-principles.md @@ -0,0 +1,105 @@ +# Quick Fix Overview + +Quick fix is a technical means provided by the OpenHarmony system for developers to fix application bugs in a manner that is far faster than application upgrades. Compared with the full application upgrade, the quick fix provides a better user experience by being smaller and faster. It allows users to fix application bugs quickly, without restarting their application. + +## Rules for Using Quick Fix + +* The quick fix only works for TypeScript (TS) and C++ code of applications, that is, .abc files (created after TS code compilation) and .so files (created after C++ code compilation). It does not work for resource files. +* No new .abc and .so files are allowed. +* Before deploying a quick fix package, make sure the corresponding application has been installed. Otherwise, the deployment will fail. +* The bundle name and application version number configured in the quick fix package must be the same as those of the installed application. Otherwise, the deployment will fail. +* Make sure the version of the quick fix package to deploy is later than that of the one previously deployed. Otherwise, the deployment will fail. +* The signature information of the quick fix package must be the same as that of the application to be fixed. Otherwise, the deployment will fail. +* Installing an application update will delete quick fix package. + +## Structure of the Quick Fix Package + +![Quick Fix Package Structure](figures/quick_fix_bundle_struct.png) +
The preceding figure shows the structure of the quick fix package released by an OpenHarmony application. +* As shown in the figure, the quick fix package comes in two formats: + * .appqf (Application Quick Fix) +
There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage). + * The .appqf file is used to release OpenHarmony applications to the application market and cannot be directly installed on devices. + * An .appqf file consists of one or more .hqf (Harmony Ability Package Quick Fix) files, which are extracted from the .appqf file by the application market and then distributed to specific devices. + * The .appqf file must contain the developer's signature information before being released to the application market. For details about how to sign the file, see [hapsigner Overview](../security/hapsigntool-overview.md). + * .hqf (Harmony Ability Package Quick Fix) +
The .hqf file is a quick fix to bugs in a HAP file. It can be installed on devices. An .hqf file contains .abc and .so files. The .abc files provide the quick fix, and the .so files provide package configuration information as well as the quick fix. + * .abc file: modified TS code in the application, which is a bytecode file created after the build. + * **libs** directory: a collection of .so.diff files, which are differential files of the .so library files, organized by system CPU architecture, such as arm and x86. + * **patch.json**: +
This file is used to describe the version information of the .hqf file and is filled in by developers. The details are as follows: + ```json + { + "app" : { + "bundleName" : "com.ohos.quickfix", + "versionCode" : 1000000, + "versionName" : "1.0.0", + "patchVersionCode" : 1000000, + "patchVersionName" : "1.0.0" + }, + "module" : { + "name" : "entry", + "type" : "patch", + "deviceTypes" : [ + "default", + "tablet" + ], + "originalModuleHash" : "11223344556677889900" + } + } + ``` + The following describes the parameters: + | Parameter|Type |Description |Initial Value Allowed| + | --- | --- | --- | --- | + |bundleName | string | Bundle name of the application. | No| + |versionCode | int |Version of the application. | No | + |versionName |string |Version name of the application.| No for the patch| + |patchVersionCode |int |Version of the patch. | No| + |patchVersionName |string |Version name of the patch.| No for the patch| + |name |string |Module name of the application, which is used to restore the module.| No| + |type | string|Type of the patch. The value can only be **patch**.| No| + |deviceTypes |array |Device types supported by the patch.| No| + |originalModuleHash| string |Hash value of the bundle corresponding to the original module name.| No| + +## Quick Fix to .abc Files Created After TS Code Compilation + +![.abc File Quick Fix](figures/quick_fix_gen_abc.png) + +The preceding figure shows the process of creating an .abc file quick fix using the TS compiler. +* An application build creates .abc and .map files. The .abc file is a bytecode file created after TS code compilation. It is used when the application is running. The .map file is an intermediate file created when the TS code is compiled using the TS compiler. It stores information such as functions and classes in the code. +* After bugs in the application are fixed, the application code is compiled again. During the compilation, the difference between the source and the target is obtained based on the preceding .map file and the current TS code, and an .abc file for quick fix is generated based on the difference. This .abc file will be placed in the .hqf file. + +## Quick Fix to .so Files Created After C++ Code Compilation + +![.so File Quickly Fix](figures/quick_fix_gen_so.png) + +The preceding figure shows the process of creating a .so file quick fix using the differential tool. +* The C++ source code of the original application is built into a .so file by using a compiler. The .so file is used when the application is running. +* After bugs in the application are fixed, the C++ code is compiled again into a .so file. With the two .so files before and after bug fixes, the differential tool generates a .so file for quick fix. This .so file will also be placed in the .hqf file. + +## Quick Fix Release and Deployment Process + +![Quick Fix File Release](figures/quick-fix-devel_release.png) + +As shown above, the modules involved in the release process are as follows: +* DevEco Studio: an integrated development environment for developing code projects. It can be used to create a quick fix file based on the original application code and the code after bug fixes, and sign the created quick repair file for release to the application market. +* Application market server: place where you release the quick fix file. It verifies the signature, scans for risks, unpacks and resigns the file, and then distributes the file to the client. +* Application market client: tool that receives the quick fix file from the application market server and triggers installation. +* Bundle manager service: system service used to manage the installation and uninstallation of application packages and quick fix files on the device. +* Quick fix engine: system service used to manage switching to quick fix code on the device. If the target application is running, the quick fix engine instructs it to switch to the quick fix file upon completion of the quick fix file deployment. +* File system: location where the application package and quick repair file are deployed on the device. + +In the end-to-end release and deployment process of the quick repair file: +1. DevEco Studio is used to create a quick fix file through building and packaging based on the original application source code and the source code after bug fixes, and sign the created quick fix file. +2. The signed quick repair file is released to the application market, which then distributes the file after verifying the signature, scanning for risks, and unpacking and resigning the file. +3. When the on-device application market client detects that a new quick fix file is available on the application market server, it downloads the file, and then installs and deploys the file through the bundle manager service in the system. +4. After the quick fix file is deployed, the quick fix engine triggers the application to switch to the quick fix file, ensuring that the user can instantly use the functions where bugs are fixed. + +## Quick Fix File Debugging Process + +![Quick Fix File Debugging](figures/quick-fix-debug.png) + +* As the quick fix capability is not yet available in DevEco Studio, for the time being, you can use the provided command-line tool to develop a quick fix file. The procedure is as follows: +1. With the original application source code and the source code after bug fixes, use the command-line tool to build and create quick fix files in .hpf format. Sign the .hpf files before installing them on the device. As aforementioned, the .appqf file cannot be installed on the device. +2. Install and deploy the .hqf files on the device using the command-line tool. +3. After the .hqf files are deployed, a callback is called to instruct the quick fix engine to trigger the application to switch to the quick fix file, ensuring that the user can instantly use the functions where bugs are fixed. diff --git a/en/application-dev/quick-start/resource-categories-and-access.md b/en/application-dev/quick-start/resource-categories-and-access.md index 56e8209a5c19e353a21b80ff8b34dd51885db310..aa5e53ae90c1794125f5b6ae8a8f7a5115128743 100644 --- a/en/application-dev/quick-start/resource-categories-and-access.md +++ b/en/application-dev/quick-start/resource-categories-and-access.md @@ -35,7 +35,7 @@ resources | Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories). | You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.
However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| +| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.
However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| | Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. | | Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. | @@ -81,9 +81,9 @@ You can create resource group subdirectories (including element, media, and prof | Resource Group Subdirectory | Description | Resource File | | ------- | ---------------------------------------- | ---------------------------------------- | -| element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows:
- **boolean**: boolean data
- **color**: color data
- **float**: floating-point data
- **intarray**: array of integers
- **integer**: integer data
- **pattern**: pattern data
- **plural**: plural form data
- **strarray**: array of strings
- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:
- boolean.json
- color.json
- float.json
- intarray.json
- integer.json
- pattern.json
- plural.json
- strarray.json
- string.json | -| media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. | -| profile | Indicates a user-defined configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. | The file name can be customized, for example, **test_profile.json**. | +| element | Indicates element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:
- **boolean**: boolean data
- **color**: color data
- **float**: floating-point data
- **intarray**: array of integers
- **integer**: integer data
- **pattern**: pattern data
- **plural**: plural form data
- **strarray**: array of strings
- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:
- boolean.json
- color.json
- float.json
- intarray.json
- integer.json
- pattern.json
- plural.json
- strarray.json
- string.json | +| media | Indicates media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. | +| profile | Indicates a custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. | | rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. | **Media Resource Types** @@ -229,7 +229,7 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile( > > Resource descriptors accept only strings, such as **'app.type.name'**, and cannot be combined. > -> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md) API. +> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) API. In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories): @@ -252,7 +252,6 @@ Text($r('app.string.message_arrive', "five'o clock")) Text($r('app.plural.eat_apple', 5, 5)) .fontColor($r('app.color.color_world')) .fontSize($r('app.float.font_world')) -} Image($r('app.media.my_background_image')) // Reference media resources. diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md deleted file mode 100644 index ff66e3d405738a44f0c645593ffb0dbfb5beca97..0000000000000000000000000000000000000000 --- a/en/application-dev/quick-start/stage-structure.md +++ /dev/null @@ -1,25 +0,0 @@ -# Application Configuration File Overview (Stage Model) - - -Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets. - - -In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files. - - -The [app.json5](app-configuration-file.md) file contains the following contents: - - -- Application-wide configuration, including the bundle name, developer, and version number. - -- Device-specific configuration. - - -The [module.json5](module-configuration-file.md) file contains the following contents: - - -- Basic module configuration, such as the name, type, description, and supported device types of the module. - -- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components. - -- Information about the permissions required during application running. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 0de7d46e88f8a4d568593616b1bf73bf4c44b95e..4f2555b95a8651ade5b99ec329033dd7bfdb184f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -125,6 +125,20 @@ - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - application - [EventHub](js-apis-inner-application-eventHub.md) + - commonEvent + - [CommonEventData](js-apis-inner-commonEvent-commonEventData.md) + - [CommonEventPublishData](js-apis-inner-commonEvent-commonEventPublishData.md) + - [CommonEventSubscriber](js-apis-inner-commonEvent-commonEventSubscriber.md) + - [CommonEventSubscribeInfo](js-apis-inner-commonEvent-commonEventSubscribeInfo.md) + - notification + - [NotificationActionButton](js-apis-inner-notification-notificationActionButton.md) + - [NotificationCommonDef](js-apis-inner-notification-notificationCommonDef.md) + - [NotificationContent](js-apis-inner-notification-notificationContent.md) + - [NotificationFlags](js-apis-inner-notification-notificationFlags.md) + - [NotificationRequest](js-apis-inner-notification-notificationRequest.md) + - [NotificationSlot](js-apis-inner-notification-notificationSlot.md) + - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) + - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) - Bundle Management - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) @@ -149,13 +163,17 @@ - [permissionDef](js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) + - UI Page - [@ohos.animator (Animator)](js-apis-animator.md) - [@ohos.curves (Interpolation Calculation)](js-apis-curve.md) - [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md) - [@ohos.mediaquery (Media Query)](js-apis-mediaquery.md) + - [@ohos.pluginComponent (PluginComponentManager)](js-apis-plugincomponent.md) - [@ohos.promptAction (Prompt)](js-apis-promptAction.md) - [@ohos.router (Page Routing)](js-apis-router.md) + - [@ohos.measure (Text Measurement)](js-apis-measure.md) + - Graphics - [@ohos.animation.windowAnimationManager (Window Animation Management)](js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](js-apis-application-windowExtensionAbility.md) @@ -168,24 +186,29 @@ - webgl - [WebGL](js-apis-webgl.md) - [WebGL2](js-apis-webgl2.md) -- Media + +- Multimedia - [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md) - [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md) - [@ohos.multimedia.camera (Camera Management)](js-apis-camera.md) - [@ohos.multimedia.image (Image Processing)](js-apis-image.md) - [@ohos.multimedia.media (Media)](js-apis-media.md) -- Resource Management + +- Resource Manager - [@ohos.i18n (Internationalization)](js-apis-i18n.md) - [@ohos.intl (Internationalization)](js-apis-intl.md) - [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md) -- Background Tasks + +- Background Task - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - + - application + - [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) + - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) @@ -194,9 +217,9 @@ - [@ohos.security.huks (HUKS)](js-apis-huks.md) - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) - - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - security - [PermissionRequestResult](js-apis-permissionrequestresult.md) + - Data Management - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) @@ -209,18 +232,19 @@ - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - data/rdb - [resultSet (Result Set)](js-apis-data-resultset.md) + - File Management - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) - [@ohos.file.fs (File Management)](js-apis-file-fs.md) - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) + - [@ohos.file.picker (Picker)](js-apis-file-picker.md) - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) - [@ohos.file.storageStatistics (Application Storage Statistics)](js-apis-file-storage-statistics.md) - [@ohos.file.volumeManager (Volume Management)](js-apis-file-volumemanager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - Telephony Service - [@ohos.contact (Contacts)](js-apis-contact.md) @@ -230,14 +254,17 @@ - [@ohos.telephony.radio (Network Search)](js-apis-radio.md) - [@ohos.telephony.sim (SIM Management)](js-apis-sim.md) - [@ohos.telephony.sms (SMS)](js-apis-sms.md) + - Network Management - [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md) - [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md) - [@ohos.net.http (Data Request)](js-apis-http.md) + - [@ohos.net.policy (Network Policy Management)](js-apis-net-policy.md) - [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md) - [@ohos.net.socket (Socket Connection)](js-apis-socket.md) - [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md) - [@ohos.request (Upload and Download)](js-apis-request.md) + - Connectivity - [@ohos.bluetooth (Bluetooth)](js-apis-bluetooth.md) - [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md) @@ -247,11 +274,12 @@ - [@ohos.rpc (RPC)](js-apis-rpc.md) - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) - [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md) - - [@ohos.wifi (To Be Deprecated)](js-apis-wifi.md) - - [@ohos.wifiext (To Be Deprecated)](js-apis-wifiext.md) + - [@ohos.wifi (To Be Deprecated Soon)](js-apis-wifi.md) + - [@ohos.wifiext (To Be Deprecated Soon)](js-apis-wifiext.md) - tag - [nfctech (Standard NFC Technologies)](js-apis-nfctech.md) - [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md) + - Basic Features - [@ohos.accessibility (Accessibility)](js-apis-accessibility.md) - [@ohos.accessibility.config (System Accessibility Configuration)](js-apis-accessibility-config.md) @@ -280,7 +308,7 @@ - [console (Log)](js-apis-logs.md) - [Timer](js-apis-timer.md) - application - - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) + - [AccessibilityExtensionContext (Accessibility Extension Context)](js-apis-inner-application-accessibilityExtensionContext.md) - imf - [InputMethodCommon](js-apis-inputmethod-InputMethodCommon.md) @@ -288,6 +316,7 @@ - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) - [@ohos.brightness (Screen Brightness)](js-apis-brightness.md) + - [@ohos.charger (Charging Type)](js-apis-charger.md) - [@ohos.deviceInfo (Device Information)](js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md) - [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md) @@ -313,19 +342,24 @@ - [@ohos.update (Update)](js-apis-update.md) - [@ohos.usbManager (USB Management)](js-apis-usbManager.md) - [@ohos.vibrator (Vibrator)](js-apis-vibrator.md) + - Account Management - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) -- Custom Management + +- Customization - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) + - [@ohos.enterprise.accountManager (Account Management)](js-apis-enterprise-accountManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md) - [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md) - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.networkManager (Network Management)](js-apis-enterprise-networkManager.md) + - [@ohos.enterprise.wifiManager (Wi-Fi Management)](js-apis-enterprise-wifiManager.md) - - Language Base Class Library +- Language Base Class Library - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml (XML-to-JavaScript Conversion)](js-apis-convertxml.md) - [@ohos.process (Obtaining Process Information)](js-apis-process.md) @@ -349,9 +383,11 @@ - [@ohos.util.Vector (Linear Container Vector)](js-apis-vector.md) - [@ohos.worker (Worker Startup)](js-apis-worker.md) - [@ohos.xml (XML Parsing and Generation)](js-apis-xml.md) + - Test - [@ohos.application.testRunner (TestRunner)](js-apis-application-testRunner.md) - [@ohos.uitest (UiTest)](js-apis-uitest.md) + - APIs No Longer Maintained - [@ohos.backgroundTaskManager (Background Task Management)](js-apis-backgroundTaskManager.md) - [@ohos.bundle (Bundle)](js-apis-Bundle.md) @@ -366,6 +402,7 @@ - [@ohos.fileio (File Management)](js-apis-fileio.md) - [@ohos.geolocation (Geolocation)](js-apis-geolocation.md) - [@ohos.hiAppEvent (Application Event Logging)](js-apis-hiappevent.md) + - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.prompt (Prompt)](js-apis-prompt.md) - [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](js-apis-statfs.md) @@ -377,6 +414,7 @@ - [@system.battery (Battery Information)](js-apis-system-battery.md) - [@system.bluetooth (Bluetooth)](js-apis-system-bluetooth.md) - [@system.brightness (Screen Brightness)](js-apis-system-brightness.md) + - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - [@system.configuration (Application Configuration)](js-apis-system-configuration.md) - [@system.device (Device Information)](js-apis-system-device.md) - [@system.fetch (Data Request)](js-apis-system-fetch.md) diff --git a/en/application-dev/reference/apis/commonEvent-definitions.md b/en/application-dev/reference/apis/commonEvent-definitions.md index b7cfc06174bbd90c193b1e98d4aa5330597a4b8f..39aa5fa3df076dde861d8020f0066f0dadd6b800 100644 --- a/en/application-dev/reference/apis/commonEvent-definitions.md +++ b/en/application-dev/reference/apis/commonEvent-definitions.md @@ -59,7 +59,7 @@ Indicates that the device screen is on and the device is in interactive state. - Required subscriber permissions: none -## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ +## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ Indicates that the device's thermal level has changed. - Value: **usual.event.THERMAL_LEVEL_CHANGED** - Required subscriber permissions: none @@ -810,7 +810,7 @@ Indicates that a USB device has been detached from the device functioning as a U ## COMMON_EVENT_DISK_BAD_REMOVAL (Reserved, not supported yet) Indicates that an external storage device was removed without being unmounted. -- Value: usual.event.data.DISK_BAD_REMOVAL +- Value: **usual.event.data.DISK_BAD_REMOVAL** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER @@ -826,33 +826,33 @@ Indicates that a USB device has been detached from the device functioning as a U - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_REMOVED9+ +## COMMON_EVENT_VOLUME_REMOVED9+ Indicates that an external storage device was removed. - Value: **usual.event.data.VOLUME_REMOVED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_UNMOUNTED9+ +## COMMON_EVENT_VOLUME_UNMOUNTED9+ Indicates that an external storage device was unmounted. - Value: **usual.event.data.VOLUME_UNMOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_MOUNTED9+ +## COMMON_EVENT_VOLUME_MOUNTED9+ Indicates that an external storage device was mounted. - Value: **usual.event.data.VOLUME_MOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ Indicates that an external storage device was removed without being unmounted. - Value: **usual.event.data.VOLUME_BAD_REMOVAL** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_EJECT9+ +## COMMON_EVENT_VOLUME_EJECT9+ Indicates that an external storage device was ejected (at the software level). -- Value: usual.event.data.VOLUME_EJECT +- **Value: usual.event.data.VOLUME_EJECT** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER @@ -880,25 +880,30 @@ Indicates that the airplane mode of the device has changed. - Required subscriber permissions: none -## COMMON_EVENT_SPLIT_SCREEN8+ +## COMMON_EVENT_SPLIT_SCREEN8+ Indicates that the screen has been split. - Value: **usual.event.SPLIT_SCREEN** - Required subscriber permissions: none -## COMMON_EVENT_SLOT_CHANGE9+ +## COMMON_EVENT_SLOT_CHANGE9+ Indicates that the notification slot has been updated. - Value: **usual.event.SLOT_CHANGE** - Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER -## COMMON_EVENT_SPN_INFO_CHANGED9+ +## COMMON_EVENT_SPN_INFO_CHANGED9+ Indicates that the SPN displayed has been updated. - Value: **usual.event.SPN_INFO_CHANGED** - Required subscriber permissions: none -## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ +## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ Indicates the result of applying a quick fix to the application. - Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Required subscriber permissions: none + +## COMMON_EVENT_USER_INFO_UPDATED9+ +Indicates that the user information has been updated. +- Value: **usual.event.USER_INFO_UPDATED** +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md index 3701910204a1a924986d9d6ff8ae144886cc5856..0670b6ca701ef78962deea0085dfbe2db1cbe863 100644 --- a/en/application-dev/reference/apis/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -59,7 +59,7 @@ Indicates that the device screen is on and the device is in interactive state. - Required subscriber permissions: none -## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ +## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ Indicates that the device's thermal level has changed. - Value: **usual.event.THERMAL_LEVEL_CHANGED** - Required subscriber permissions: none @@ -658,6 +658,10 @@ Indicates that the system starts charging the battery. - Value: **usual.event.CHARGING** - Required subscriber permissions: none +## COMMON_EVENT_CHARGE_TYPE_CHANGED +Indicates that the system charging type has changed. This event is available only for system applications. +- Value: **usual.event.CHARGE_TYPE_CHANGED** +- Required subscriber permissions: none ## COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED (Reserved, not supported yet) Indicates that the system idle mode has changed. @@ -845,31 +849,31 @@ Indicates that a USB device has been detached from the device functioning as a U - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_REMOVED9+ +## COMMON_EVENT_VOLUME_REMOVED9+ Indicates that an external storage device was removed. - Value: **usual.event.data.VOLUME_REMOVED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_UNMOUNTED9+ +## COMMON_EVENT_VOLUME_UNMOUNTED9+ Indicates that an external storage device was unmounted. - Value: **usual.event.data.VOLUME_UNMOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_MOUNTED9+ +## COMMON_EVENT_VOLUME_MOUNTED9+ Indicates that an external storage device was mounted. - Value: **usual.event.data.VOLUME_MOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ Indicates that an external storage device was removed without being unmounted. - Value: **usual.event.data.VOLUME_BAD_REMOVAL** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_EJECT9+ +## COMMON_EVENT_VOLUME_EJECT9+ Indicates that an external storage device was ejected (at the software level). - Value: usual.event.data.VOLUME_EJECT - Required subscriber permissions: ohos.permission.STORAGE_MANAGER @@ -905,23 +909,23 @@ Indicates that the screen has been split. - Required subscriber permissions: ohos.permission.RECEIVER_SPLIT_SCREEN -## COMMON_EVENT_SLOT_CHANGE9+ +## COMMON_EVENT_SLOT_CHANGE9+ Indicates that the notification slot has been updated. - Value: **usual.event.SLOT_CHANGE** - Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER -## COMMON_EVENT_SPN_INFO_CHANGED9+ +## COMMON_EVENT_SPN_INFO_CHANGED9+ Indicates that the SPN displayed has been updated. - Value: **usual.event.SPN_INFO_CHANGED** - Required subscriber permissions: none -## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ +## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ Indicates the result of applying a quick fix to the application. - Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Required subscriber permissions: none -## COMMON_EVENT_HTTP_PROXY_CHANGE10+ +## COMMON_EVENT_HTTP_PROXY_CHANGE10+ Indicates that the HTTP proxy configuration has changed. - Value: **usual.event.HTTP_PROXY_CHANGE** - Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/figures/Colorsucker.png b/en/application-dev/reference/apis/figures/Colorsucker.png new file mode 100644 index 0000000000000000000000000000000000000000..40e19e94e129682fdeb461cceef0f0a57c64d66d Binary files /dev/null and b/en/application-dev/reference/apis/figures/Colorsucker.png differ diff --git a/en/application-dev/reference/apis/figures/Copy.png b/en/application-dev/reference/apis/figures/Copy.png new file mode 100644 index 0000000000000000000000000000000000000000..212517131bf176661ae85c7513def022dbb50559 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Copy.png differ diff --git a/en/application-dev/reference/apis/figures/Cross.png b/en/application-dev/reference/apis/figures/Cross.png new file mode 100644 index 0000000000000000000000000000000000000000..58625855d1cd96ea8a29ab9c3c201d90ac717e83 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Cross.png differ diff --git a/en/application-dev/reference/apis/figures/Default.png b/en/application-dev/reference/apis/figures/Default.png new file mode 100644 index 0000000000000000000000000000000000000000..6308171fe9d612050376f6a5dfdc870e51bc92db Binary files /dev/null and b/en/application-dev/reference/apis/figures/Default.png differ diff --git a/en/application-dev/reference/apis/figures/East.png b/en/application-dev/reference/apis/figures/East.png new file mode 100644 index 0000000000000000000000000000000000000000..4942bc948a17e78c68538ccc3ae886bc0a548737 Binary files /dev/null and b/en/application-dev/reference/apis/figures/East.png differ diff --git a/en/application-dev/reference/apis/figures/Forbid.png b/en/application-dev/reference/apis/figures/Forbid.png new file mode 100644 index 0000000000000000000000000000000000000000..c5c43d4b4b8aaf6d53931586e519a583d064fec7 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Forbid.png differ diff --git a/en/application-dev/reference/apis/figures/Hand_Grabbing.png b/en/application-dev/reference/apis/figures/Hand_Grabbing.png new file mode 100644 index 0000000000000000000000000000000000000000..09ab3121d15e27a975fbaa228aadb2399e4492b9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Hand_Grabbing.png differ diff --git a/en/application-dev/reference/apis/figures/Hand_Open.png b/en/application-dev/reference/apis/figures/Hand_Open.png new file mode 100644 index 0000000000000000000000000000000000000000..e1cb7a972ec2d372f0d75cbe80159c4a66e74e10 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Hand_Open.png differ diff --git a/en/application-dev/reference/apis/figures/Hand_Pointing.png b/en/application-dev/reference/apis/figures/Hand_Pointing.png new file mode 100644 index 0000000000000000000000000000000000000000..f0daa0dad6154a1846fb9fe4b7f441b3ab6f8b5b Binary files /dev/null and b/en/application-dev/reference/apis/figures/Hand_Pointing.png differ diff --git a/en/application-dev/reference/apis/figures/Help.png b/en/application-dev/reference/apis/figures/Help.png new file mode 100644 index 0000000000000000000000000000000000000000..ffea2f1c072f1682ca8e837ddb947352a553917e Binary files /dev/null and b/en/application-dev/reference/apis/figures/Help.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_East.png b/en/application-dev/reference/apis/figures/MID_Btn_East.png new file mode 100644 index 0000000000000000000000000000000000000000..921cd4ceea8d97ffb6d4c45008d6428cda998cce Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_East.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_North.png b/en/application-dev/reference/apis/figures/MID_Btn_North.png new file mode 100644 index 0000000000000000000000000000000000000000..5769575ddb435f5e8f5f8993d9edc13749376293 Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_North.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_North_East.png b/en/application-dev/reference/apis/figures/MID_Btn_North_East.png new file mode 100644 index 0000000000000000000000000000000000000000..3daf141241dec309c98ae10266bb153af163f3d9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_North_East.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_North_South.png b/en/application-dev/reference/apis/figures/MID_Btn_North_South.png new file mode 100644 index 0000000000000000000000000000000000000000..1f56c4cd8f1498293f5fc4a5ab2c321159fb07dd Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_North_South.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_North_South_West_East.png b/en/application-dev/reference/apis/figures/MID_Btn_North_South_West_East.png new file mode 100644 index 0000000000000000000000000000000000000000..b45dbde27e59121bdfc4e1752759176fb835027c Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_North_South_West_East.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_North_West.png b/en/application-dev/reference/apis/figures/MID_Btn_North_West.png new file mode 100644 index 0000000000000000000000000000000000000000..bde82d08f7a098106b4f4c31d55a84a989e25a8d Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_North_West.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_South.png b/en/application-dev/reference/apis/figures/MID_Btn_South.png new file mode 100644 index 0000000000000000000000000000000000000000..e7d5afb6f8f8b1b2939b9e18bdb8b8b3d9729f4d Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_South.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_South_East.png b/en/application-dev/reference/apis/figures/MID_Btn_South_East.png new file mode 100644 index 0000000000000000000000000000000000000000..44284a6e04a19ca8453b46ea81db099ad84cfaa2 Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_South_East.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_South_West.png b/en/application-dev/reference/apis/figures/MID_Btn_South_West.png new file mode 100644 index 0000000000000000000000000000000000000000..c8632f09160c51ca573d58d3ffb1370058b880ce Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_South_West.png differ diff --git a/en/application-dev/reference/apis/figures/MID_Btn_West.png b/en/application-dev/reference/apis/figures/MID_Btn_West.png new file mode 100644 index 0000000000000000000000000000000000000000..7460bc18d63e000689755b39b8ead3c3609ee4f5 Binary files /dev/null and b/en/application-dev/reference/apis/figures/MID_Btn_West.png differ diff --git a/en/application-dev/reference/apis/figures/Move.png b/en/application-dev/reference/apis/figures/Move.png new file mode 100644 index 0000000000000000000000000000000000000000..00f64e54dca0d0731b595b4ddc9e0f7294c40c72 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Move.png differ diff --git a/en/application-dev/reference/apis/figures/North.png b/en/application-dev/reference/apis/figures/North.png new file mode 100644 index 0000000000000000000000000000000000000000..b022ac2e92d4cfb07efde7f3bf4b7ada8454e594 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North.png differ diff --git a/en/application-dev/reference/apis/figures/North_East.png b/en/application-dev/reference/apis/figures/North_East.png new file mode 100644 index 0000000000000000000000000000000000000000..f6134237f38cd681b319c95bf1b77017bc1524b4 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North_East.png differ diff --git a/en/application-dev/reference/apis/figures/North_East_South_West.png b/en/application-dev/reference/apis/figures/North_East_South_West.png new file mode 100644 index 0000000000000000000000000000000000000000..908886aeb3f8df976bb67b2261e8e52e7222e622 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North_East_South_West.png differ diff --git a/en/application-dev/reference/apis/figures/North_South.png b/en/application-dev/reference/apis/figures/North_South.png new file mode 100644 index 0000000000000000000000000000000000000000..b15678a6b178ca0d9b13f7c7f58d025ab7a1ce12 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North_South.png differ diff --git a/en/application-dev/reference/apis/figures/North_West.png b/en/application-dev/reference/apis/figures/North_West.png new file mode 100644 index 0000000000000000000000000000000000000000..cfbe4c8910575c12afde4b5904d79b5beda0c162 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North_West.png differ diff --git a/en/application-dev/reference/apis/figures/North_West_South_East.png b/en/application-dev/reference/apis/figures/North_West_South_East.png new file mode 100644 index 0000000000000000000000000000000000000000..09fa728fbb45082a0524c284b8906b91d7b3a6f7 Binary files /dev/null and b/en/application-dev/reference/apis/figures/North_West_South_East.png differ diff --git a/en/application-dev/reference/apis/figures/Resize_Left_Right.png b/en/application-dev/reference/apis/figures/Resize_Left_Right.png new file mode 100644 index 0000000000000000000000000000000000000000..83e7671e3ffea65260bdb36d8b392fa78d55cd4e Binary files /dev/null and b/en/application-dev/reference/apis/figures/Resize_Left_Right.png differ diff --git a/en/application-dev/reference/apis/figures/Resize_Up_Down.png b/en/application-dev/reference/apis/figures/Resize_Up_Down.png new file mode 100644 index 0000000000000000000000000000000000000000..db8bccf89b6e5260db3875a22b5200fabd30c23c Binary files /dev/null and b/en/application-dev/reference/apis/figures/Resize_Up_Down.png differ diff --git a/en/application-dev/reference/apis/figures/Screenshot_Cross.png b/en/application-dev/reference/apis/figures/Screenshot_Cross.png new file mode 100644 index 0000000000000000000000000000000000000000..27460c082507e71082d11cd8a20eee2fc24da28d Binary files /dev/null and b/en/application-dev/reference/apis/figures/Screenshot_Cross.png differ diff --git a/en/application-dev/reference/apis/figures/Screenshot_Cursor.png b/en/application-dev/reference/apis/figures/Screenshot_Cursor.png new file mode 100644 index 0000000000000000000000000000000000000000..71abea4ca351988a92b8a5b2b2228321df31aecc Binary files /dev/null and b/en/application-dev/reference/apis/figures/Screenshot_Cursor.png differ diff --git a/en/application-dev/reference/apis/figures/South.png b/en/application-dev/reference/apis/figures/South.png new file mode 100644 index 0000000000000000000000000000000000000000..205f5cf5f59ce8318357e168eee0d66c119c233d Binary files /dev/null and b/en/application-dev/reference/apis/figures/South.png differ diff --git a/en/application-dev/reference/apis/figures/South_East.png b/en/application-dev/reference/apis/figures/South_East.png new file mode 100644 index 0000000000000000000000000000000000000000..f4a70d2d068271bfe10e4ce724ae27e4e5ba96d9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/South_East.png differ diff --git a/en/application-dev/reference/apis/figures/South_West.png b/en/application-dev/reference/apis/figures/South_West.png new file mode 100644 index 0000000000000000000000000000000000000000..2ae8e9a9fa396bb6ed0f385b7b99b66830357a40 Binary files /dev/null and b/en/application-dev/reference/apis/figures/South_West.png differ diff --git a/en/application-dev/reference/apis/figures/Text_Cursor.png b/en/application-dev/reference/apis/figures/Text_Cursor.png new file mode 100644 index 0000000000000000000000000000000000000000..7cd8d2200bc7455e562da003069702832db4eb20 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Text_Cursor.png differ diff --git a/en/application-dev/reference/apis/figures/West.png b/en/application-dev/reference/apis/figures/West.png new file mode 100644 index 0000000000000000000000000000000000000000..2cad91aca31f2e2b257c523e80e6fc2d71fa2cee Binary files /dev/null and b/en/application-dev/reference/apis/figures/West.png differ diff --git a/en/application-dev/reference/apis/figures/West_East.png b/en/application-dev/reference/apis/figures/West_East.png new file mode 100644 index 0000000000000000000000000000000000000000..6be4aa9d05f22a10cd00fa6aec36f95aee2b332d Binary files /dev/null and b/en/application-dev/reference/apis/figures/West_East.png differ diff --git a/en/application-dev/reference/apis/figures/Zoom_In.png b/en/application-dev/reference/apis/figures/Zoom_In.png new file mode 100644 index 0000000000000000000000000000000000000000..2e928ec070fcd05a44cd9b1abd041128287b0528 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Zoom_In.png differ diff --git a/en/application-dev/reference/apis/figures/Zoom_Out.png b/en/application-dev/reference/apis/figures/Zoom_Out.png new file mode 100644 index 0000000000000000000000000000000000000000..d675d0e517ba436724540a39f60dfa75c256f0d0 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Zoom_Out.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG index 14f81499ff0b1b8ef46257bc35a79e94775cd2ba..54be7ed38fa40349036e18b962ee52deb579a033 100644 Binary files a/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG and b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index f537fc5fe11a199afab4821b29b199499faa6c97..0051896a67f1dd2c9e662ed1ac503259ad6a7997 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -157,7 +157,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead. -getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> +getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\\> Obtains the information of all bundles of the specified user. This API uses a promise to return the result. @@ -201,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead. -getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\\>): void Obtains the information of all bundles of the current user. This API uses an asynchronous callback to return the result. @@ -238,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead. -getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\\>): void Obtains the information of all bundles of the specified user. This API uses an asynchronous callback to return the result. @@ -823,7 +823,7 @@ bundle.getPermissionDef(permissionName).then((data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead. -getAllApplicationInfo(bundleFlags: number, userId?: number): Promise> +getAllApplicationInfo(bundleFlags: number, userId?: number): Promise\\> Obtains the information about all applications of the specified user. This API uses a promise to return the result. @@ -865,7 +865,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead. -getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void +getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback\\>): void Obtains the information about all applications. This API uses an asynchronous callback to return the result. @@ -1320,7 +1320,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. -queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> +queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise\\> Obtains the ability information based on given Want. This API uses a promise to return the result. @@ -1371,7 +1371,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. -queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void +queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\\>): void Obtains the ability information of the specified user based on given Want. This API uses an asynchronous callback to return the result. @@ -1416,7 +1416,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. -queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; +queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback\\>): void; Obtains the ability information based on given Want. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index a22f7b48a977066e085da4b9ddfcdeb24f21463f..33555ada83df3e20766793df3208f250ac612a00 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' ``` +## Attributes + +**System capability**: SystemCapability.ResourceSchedule.WorkScheduler + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) | Yes| No| Context of the **WorkSchedulerExtension**. This context is inherited from **ExtensionContext**.| + ## WorkSchedulerExtensionAbility.onWorkStart onWorkStart(work: workScheduler.WorkInfo): void diff --git a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md index 836f07ef61ee7b5801fe86b3dbbaed72c017e466..262899f64ed644007d28d1dce9b53c369a830f12 100644 --- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -57,8 +57,12 @@ featureAbility.startAbility( uri: '' }, }, - (err, data) => { - console.info('startAbility err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('startAbility fail, error: ${JSON.stringify(error)}'); + } else { + console.log('startAbility success, data: ${JSON.stringify(data)}'); + } } ); ``` @@ -99,7 +103,7 @@ featureAbility.startAbility( { want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -182,7 +186,7 @@ featureAbility.startAbilityForResult( { want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -193,8 +197,12 @@ featureAbility.startAbilityForResult( uri:'' }, }, - (err, data) => { - console.info('startAbilityForResult err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('startAbilityForResult fail, error: ${JSON.stringify(error)}'); + } else { + console.log('startAbilityForResult success, data: ${JSON.stringify(data)}'); + } } ); ``` @@ -236,7 +244,7 @@ featureAbility.startAbilityForResult( { want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -288,7 +296,7 @@ featureAbility.terminateSelfWithResult( resultCode: 1, want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -309,8 +317,8 @@ featureAbility.terminateSelfWithResult( } }, }, - (err) => { - console.error('err: ${JSON.stringify(err)}'); + (error) => { + console.error('error: ${JSON.stringify(error)}'); } ); ``` @@ -345,7 +353,7 @@ featureAbility.terminateSelfWithResult( resultCode: 1, want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -389,8 +397,12 @@ Checks whether the main window of this ability has the focus. This API uses an a ```ts import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.hasWindowFocus((err, data) => { - console.info('hasWindowFocus err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +featureAbility.hasWindowFocus((error, data) => { + if (error && error.code !== 0) { + console.error('hasWindowFocus fail, error: ${JSON.stringify(error)}'); + } else { + console.log('hasWindowFocus success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -435,8 +447,12 @@ Obtains the Want corresponding to the ability to start. This API uses an asynchr ```ts import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.getWant((err, data) => { - console.info('getWant err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +featureAbility.getWant((error, data) => { + if (error && error.code !== 0) { + console.error('getWant fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getWant success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -482,8 +498,12 @@ Obtains the application context. ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getBundleName((err, data) => { - console.info('getBundleName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getBundleName((error, data) => { + if (error && error.code !== 0) { + console.error('getBundleName fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getBundleName success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -506,8 +526,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf( - (err) => { - console.error('err: ${JSON.stringify(err)}'); + (error) => { + console.error('error: ${JSON.stringify(error)}'); } ) ``` @@ -574,7 +594,7 @@ function onDisconnectCallback(element){ console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}') } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}') + console.error('featureAbilityTest ConnectAbility onFailed errCode : ${code}') } let connectId = featureAbility.connectAbility( { @@ -617,7 +637,7 @@ function onDisconnectCallback(element){ console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); + console.error('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); } let connectId = featureAbility.connectAbility( { @@ -631,8 +651,12 @@ let connectId = featureAbility.connectAbility( }, ); -featureAbility.disconnectAbility(connectId, (err) => { - console.error('featureAbilityTest disconnectAbility err: ${JSON.stringify(err)}'); +featureAbility.disconnectAbility(connectId, (error) => { + if (error && error.code !== 0) { + console.error('disconnectAbility fail, connectId: ${connectId}, error: ${JSON.stringify(error)}'); + } else { + console.log('disconnectAbility success, connectId: ${connectId}'); + } }); ``` @@ -668,7 +692,7 @@ function onDisconnectCallback(element){ console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); + console.error('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); } let connectId = featureAbility.connectAbility( { @@ -707,8 +731,12 @@ Obtains the window corresponding to this ability. This API uses an asynchronous **Example** ```ts -featureAbility.getWindow((err, data) => { - console.info('getWindow err: ${JSON.stringify(err)}, data: ${typeof(data)}'); +featureAbility.getWindow((error, data) => { + if (error && error.code !== 0) { + console.error('getWindow fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getWindow success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -823,6 +851,6 @@ Enumerates the flags that specify how the Want will be handled. | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for [Want](js-apis-application-want.md) under the [parameter](js-apis-inner-ability-startAbilityParameter.md) object passed to the [startAbility](#featureabilitystartability) API in **FeatureAbility**. It must be used together with **flag_ABILITY_NEW_MISSION**.| | FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on an existing mission stack. | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md index d4c5a739a80f7976f1581454423cc8c4d824035d..1afa116d859733011cd323f6eda58b7dea225d96 100644 --- a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -47,7 +47,7 @@ particleAbility.startAbility( { want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -57,8 +57,12 @@ particleAbility.startAbility( uri: '' }, }, - (error, result) => { - console.error('particleAbility startAbility errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('startAbility fail, error: ${JSON.stringify(error)}'); + } else { + console.log('startAbility success, data: ${JSON.stringify(data)}'); + } }, ); ``` @@ -98,7 +102,7 @@ particleAbility.startAbility( { want: { - action: 'action.system.home', + action: 'ohos.want.action.home', entities: ['entity.system.home'], type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, @@ -133,8 +137,12 @@ Terminates this ParticleAbility. This API uses an asynchronous callback to retur import particleAbility from '@ohos.ability.particleAbility'; particleAbility.terminateSelf( - (error, result) => { - console.log('particleAbility terminateSelf errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('terminateSelf fail, error: ${JSON.stringify(error)}'); + } else { + console.log('terminateSelf success, data: ${JSON.stringify(data)}'); + } } ); ``` @@ -226,11 +234,11 @@ import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.app.ability.wantAgent'; -function callback(err, data) { - if (err) { - console.error('Operation failed cause: ${JSON.stringify(err)}'); +function callback(error, data) { + if (error && error.code !== 0) { + console.error('Operation failed error: ${JSON.stringify(error)}'); } else { - console.info('Operation succeeded'); + console.info('Operation succeeded, data: ${data}'); } } @@ -349,11 +357,11 @@ Requests to cancel a continuous task from the system. This API uses an asynchron ```ts import particleAbility from '@ohos.ability.particleAbility'; -function callback(err, data) { - if (err) { - console.error('Operation failed cause: ${JSON.stringify(err)}'); +function callback(error, data) { + if (error && error.code !== 0) { + console.error('Operation failed error: ${JSON.stringify(error)}'); } else { - console.info('Operation succeeded'); + console.info('Operation succeeded, data: ${data}'); } } @@ -421,11 +429,11 @@ function onConnectCallback(element, remote) { } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); + console.log('ConnectAbility onDisconnect element.deviceId: ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); + console.error('particleAbilityTest ConnectAbility onFailed errCode: ${code}'); } let connId = particleAbility.connectAbility( @@ -441,9 +449,9 @@ let connId = particleAbility.connectAbility( ); particleAbility.disconnectAbility(connId).then((data) => { - console.log(' data: ${data}'); + console.log('data: ${data}'); }).catch((error) => { - console.log('particleAbilityTest result errCode : ${error.code}'); + console.error('particleAbilityTest result errCode: ${error.code}'); }); ``` @@ -472,11 +480,11 @@ function onConnectCallback(element, remote) { } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); + console.log('ConnectAbility onDisconnect element.deviceId: ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); + console.error('particleAbilityTest ConnectAbility onFailed errCode: ${code}'); } let connId = particleAbility.connectAbility( @@ -492,7 +500,7 @@ let connId = particleAbility.connectAbility( ); particleAbility.disconnectAbility(connId, (err) => { - console.log('particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}'); + console.error('particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}'); }); ``` @@ -522,11 +530,11 @@ function onConnectCallback(element, remote) { } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); + console.log('ConnectAbility onDisconnect element.deviceId: ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); + console.error('particleAbilityTest ConnectAbility onFailed errCode: ${code}'); } let connId = particleAbility.connectAbility( @@ -544,7 +552,7 @@ let connId = particleAbility.connectAbility( particleAbility.disconnectAbility(connId).then((data) => { console.log(' data: ${data}'); }).catch((error) => { - console.log('particleAbilityTest result errCode : ${error.code}'); + console.error('particleAbilityTest result errCode : ${error.code}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 776faa162b5178cec3bf003aedc018c17ab17084..55074a510f56e2580d8e57da59ca72bb3209876f 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -46,13 +46,6 @@ Enumerates the action constants of the **Want** object. **action** specifies the | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | | PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. The value must be an array of the string type. | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | -| ACTION_APP_ACCOUNT_AUTH 9+ | account.appAccount.action.auth | Action of providing the authentication service. | -| ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | -| ACTION_MARKET_CROWDTEST 9+ | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_SANDBOX9+ |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_BUNDLE_NAME9+ |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_MODULE_NAME9+ |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_ABILITY_NAME9+ |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications. | | DLP_PARAMS_INDEX9+ |ohos.dlp.params.index |Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications. | ## wantConstant.Entity @@ -72,7 +65,7 @@ Enumerates the entity constants of the **Want** object. **entity** specifies add ## wantConstant.Flags -Enumerates the flags that specify how the Want will be handled. + Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase @@ -91,6 +84,6 @@ Enumerates the flags that specify how the Want will be handled. | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for **Want** in the [startAbility](js-apis-ability-featureAbility.md#startability) API passed to the FeatureAbility module. It must be used together with **flag_ABILITY_NEW_MISSION**. | | FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index ff89b62d12e370ccaa046c40576405e8cfe72c22..54cea921d80648b17fe5384e4ea9e57336d32fc1 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -3,6 +3,7 @@ The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. > **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -15,7 +16,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl' createAtManager(): AtManager -Creates an **AtManager** instance, which is used for ability access control. +Creates an **AtManager** instance, which is used for application access control. **System capability**: SystemCapability.Security.AccessToken @@ -34,7 +35,7 @@ let atManager = abilityAccessCtrl.createAtManager(); ## AtManager -Implements ability access control. +Provides APIs for application access control. ### checkAccessToken9+ @@ -59,11 +60,11 @@ Checks whether a permission is granted to an application. This API uses a promis **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | **Example** @@ -106,11 +107,11 @@ Verifies whether a permission is granted to an application. This API returns the **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | **Example** @@ -123,7 +124,7 @@ console.log(`data->${JSON.stringify(data)}`); ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number): Promise<void> +grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlags: number): Promise<void> Grants a user_grant permission to an application. This API uses a promise to return the result. @@ -139,7 +140,7 @@ Grants a user_grant permission to an application. This API uses a promise to ret | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | | permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| -| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlags | number | Yes | Permission flag.
- **0**: The permission is not set by the user.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **4**: The permission is authorized by the system and cannot be changed.| **Return value** @@ -149,11 +150,11 @@ Grants a user_grant permission to an application. This API uses a promise to ret **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -166,9 +167,9 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let permissionFlag = 1; +let permissionFlags = 1; try { - atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags).then(() => { console.log('grantUserGrantedPermission success'); }).catch((err) => { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -180,7 +181,7 @@ try { ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number, callback: AsyncCallback<void>): void +grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlags: number, callback: AsyncCallback<void>): void Grants a user_grant permission to an application. This API uses an asynchronous callback to return the result. @@ -196,16 +197,16 @@ Grants a user_grant permission to an application. This API uses an asynchronous | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| | permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| -| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefined**. Otherwise, **err** is an error object.| +| permissionFlags | number | Yes | Permission flag.
- **0**: The permission is not set by the user.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **4**: The permission is authorized by the system and cannot be changed.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the permission is granted, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -218,9 +219,9 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let permissionFlag = 1; +let permissionFlags = 1; try { - atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { + atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags, (err, data) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -234,7 +235,7 @@ try { ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number): Promise<void> +revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlags: number): Promise<void> Revokes a user_grant permission from an application. This API uses a promise to return the result. @@ -250,7 +251,7 @@ Revokes a user_grant permission from an application. This API uses a promise to | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | | permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| -| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlags | number | Yes | Permission flag.
- **0**: The permission is not set by the user.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **4**: The permission is authorized by the system and cannot be changed.| **Return value** @@ -260,11 +261,11 @@ Revokes a user_grant permission from an application. This API uses a promise to **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -277,9 +278,9 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let permissionFlag = 1; +let permissionFlags = 1; try { - atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags).then(() => { console.log('revokeUserGrantedPermission success'); }).catch((err) => { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -291,7 +292,7 @@ try { ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number, callback: AsyncCallback<void>): void +revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlags: number, callback: AsyncCallback<void>): void Revokes a user_grant permission from an application. This API uses an asynchronous callback to return the result. @@ -307,16 +308,16 @@ Revokes a user_grant permission from an application. This API uses an asynchrono | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | | permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| -| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefined**. Otherwise, **err** is an error object.| +| permissionFlags | number | Yes | Permission flag.
- **0**: The permission is not set by the user.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **4**: The permission is authorized by the system and cannot be changed.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the permission is revoked, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -329,9 +330,9 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let permissionFlag = 1; +let permissionFlags = 1; try { - atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { + atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags, (err, data) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -347,7 +348,7 @@ try { getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<number> -Obtains the flags of the specified permission of an application. This API uses a promise to return the result. +Obtains the permission flag of an application. This API uses a promise to return the result. **System API**: This is a system API. @@ -366,15 +367,15 @@ Obtains the flags of the specified permission of an application. This API uses a | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the result.| +| Promise<number> | Promise used to return the permission flag obtained. | **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | @@ -426,9 +427,9 @@ promise.then(data => { ### on9+ -on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void; +on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void; -Subscribes to permission grant state changes of the specified applications and permissions. +Subscribes to permission state changes of the specified applications and permissions. **System API**: This is a system API. @@ -440,18 +441,18 @@ Subscribes to permission grant state changes of the specified applications and p | 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> | Yes | List of token IDs. If this parameter is left empty, the permission grant state changes of all applications are subscribed to. | -| permissionNameList | Array<Permissions> | Yes | 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.| +| type | string | Yes | Event type to subscribe to. The value is **'permissionStateChange'**, which indicates the permission grant state change. | +| tokenIDList | Array<number> | Yes | Token IDs of the applications to observe. If this parameter is left empty, the permission grant state changes of all applications are observed. | +| permissionList | Array<Permissions> | Yes | Permissions to observe. If this parameter is left empty, the grant state changes of all permissions are observed. | +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | Yes| Callback invoked to return the permission grant state change.| **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100004 | The interface is called repeatedly with the same input. | | 12100005 | The registration time has exceeded the limitation. | | 12100007 | Service is abnormal. | @@ -461,13 +462,14 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import bundle from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; -let permissionNameList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; +let permissionList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; try { - atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { + atManager.on('permissionStateChange', tokenIDList, permissionList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -477,9 +479,9 @@ try { ### off9+ -off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<Permissions>, callback?: Callback<PermissionStateChangeInfo>): void; +off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionList: Array<Permissions>, callback?: Callback<PermissionStateChangeInfo>): void; -Unsubscribes from permission grant state changes of the specified applications and permissions. This API uses an asynchronous callback to return the result. +Unsubscribes from permission grant state changes of the specified applications and permissions. This API uses a callback to return the result. **System API**: This is a system API. @@ -491,19 +493,19 @@ Unsubscribes from permission grant state changes of the specified applications a | 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> | Yes | 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<Permissions> | Yes | 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.| +| type | string | Yes | Event type to unsubscribe from. The value is **'permissionStateChange'**, which indicates the permission grant state change. | +| tokenIDList | Array<number> | Yes | Token IDs of the applications. 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()**. | +| permissionList | Array<Permissions> | Yes | Permission names. If this parameter is left empty, the 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 for the permission grant state change. | **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID in list is all invalid | -| 12100004 | The interface is not used with | +| 12100001 | The parameter is invalid. The tokenID in list is all invalid, or the permissionName in list is all invalid. | +| 12100004 | The API is not used together with "on()". | | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | @@ -511,13 +513,14 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import bundle from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; -let permissionNameList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; +let permissionList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; try { - atManager.off('permissionStateChange', tokenIDList, permissionNameList); + atManager.off('permissionStateChange', tokenIDList, permissionList); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } @@ -538,7 +541,7 @@ Verifies whether a permission is granted to an application. This API uses a prom | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | | tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | -| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). | **Return value** @@ -561,9 +564,9 @@ promise.then(data => { ### requestPermissionsFromUser9+ -requestPermissionsFromUser(context: Context, permissions: Array<Permissions>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; +requestPermissionsFromUser(context: Context, permissionList: Array<Permissions>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; -Requests user authorization in a dialog box. This API uses an asynchronous callback to return the result. +Requests permissions from the user in a dialog box. This API uses an asynchronous callback to return the result. **Model restriction**: This API can be used only in the stage model. @@ -573,16 +576,17 @@ Requests user authorization in a dialog box. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Ability context of the application that requests the permission.| -| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| context | Context | Yes| Ability context of the application that requests the permissions. | +| permissionList | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback invoked to return the result.| **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | +| 12100001 | The parameter is invalid. The context is invalid when it does not belong to the application itself. | **Example** @@ -602,9 +606,9 @@ try { ### requestPermissionsFromUser9+ -requestPermissionsFromUser(context: Context, permissions: Array<Permissions>) : Promise<PermissionRequestResult>; +requestPermissionsFromUser(context: Context, permissionList: Array<Permissions>) : Promise<PermissionRequestResult>; -Requests user authorization in a dialog box. This API uses a promise to return the result. +Requests permissions from the user in a dialog box. This API uses a promise to return the result. **Model restriction**: This API can be used only in the stage model. @@ -614,8 +618,8 @@ Requests user authorization in a dialog box. This API uses a promise to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Ability context of the application that requests the permission.| -| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| context | Context | Yes| Ability context of the application that requests the permissions. | +| permissionList | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). | **Return value** @@ -625,10 +629,11 @@ Requests user authorization in a dialog box. This API uses a promise to return **Error codes** -For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | +| 12100001 | The parameter is invalid. The context is invalid when it does not belong to the application itself. | **Example** @@ -710,7 +715,7 @@ Enumerates the operations that trigger permission grant state changes. ### PermissionStateChangeInfo9+ -Defines the detailed permission grant state change information. +Defines detailed information about the permission grant state change. **System API**: This is a system API. @@ -719,5 +724,6 @@ Defines the detailed permission grant state change information. | 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 | Permissions | Yes | No | Permission whose authorization status changes. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| tokenID | number | Yes | No | Token ID of the application. | +| permissionName | Permissions | Yes | No | Permission whose grant state changes. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). | + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 62d38c714940a754e566bbdebadac2e3fcbccec2..ff1bbfa2187c2a5ad868e28e11e08ae1a77ed705 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -35,8 +35,8 @@ Enumerates the initial ability launch reasons. You can use it together with [onC | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| -| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-ability-context.md#abilitycontextstartability).| -| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall).| +| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).| +| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall).| | CONTINUATION | 3 | The ability is started by means of cross-device migration.| | APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.| @@ -99,7 +99,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onContinue(wantParam) { - return AbilityConstant.OnConinueResult.AGREE; + return AbilityConstant.OnContinueResult.AGREE; } } ``` @@ -132,10 +132,10 @@ let option = { }; // Ensure that the context is obtained. -this.context.startAbility(want, option).then(()={ +this.context.startAbility(want, option).then(()=>{ console.log('Succeed to start ability.'); }).catch((error)=>{ - console.log('Failed to start ability with error: ${JSON.stringify(error)}'); + console.error('Failed to start ability with error: ${JSON.stringify(error)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index fe6bec9f550bef9bdeb6a3c61c8a1c5adc810f10..76614085293fe0065dafea4a2e3a9d0d8559be0f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -56,7 +56,7 @@ abilityDelegator.startAbility(want, (err) => { if (!err || err.code === 0) { console.log('Success start ability.'); } else { - console.log('Failed start ability, error: ${JSON.stringify(err)}'); + console.error('Failed start ability, error: ${JSON.stringify(err)}'); } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index df7b07b2d0303bf9310cfdd354d50b1db9239ece..28c0772d7d5718cd328f318535bb276ff32550cf 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -275,9 +275,9 @@ export default class MyFirstAbility extends UIAbility { // 2. Register the listener for the ability lifecycle changes through the applicationContext object. try { globalThis.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); - console.log('registerAbilityLifecycleCallback number: ${JSON.stringify(lifecycleId)}'); + console.log('registerAbilityLifecycleCallback lifecycleId: ${globalThis.lifecycleId}'); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } } } @@ -285,7 +285,7 @@ export default class MyFirstAbility extends UIAbility { MySecondAbility.ts ```ts -import UIAbility from 'ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; export default class MySecondAbility extends UIAbility { onDestroy() { @@ -293,7 +293,7 @@ export default class MySecondAbility extends UIAbility { // 3. Deregister the listener for the ability lifecycle changes through the applicationContext object. applicationContext.off('abilityLifecycle', globalThis.lifecycleId, (error) => { if (error && error.code !== 0) { - console.log('unregisterAbilityLifecycleCallback fail, error: ${JSON.stringify(error)}'); + console.error('unregisterAbilityLifecycleCallback fail, error: ${JSON.stringify(error)}'); } else { console.log('unregisterAbilityLifecycleCallback success.'); } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index 3bfd14ef61cbd5995d4d5b8a0e93a08cfbeaaac5..73d21161ce9aa37f7242b49f615759e547c1925a 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -59,12 +59,13 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import abilityManager from '@ohos.app.ability.abilityManager'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; const config = { language: 'Zh-Hans', // Simplified Chinese. - colorMode: COLOR_MODE_LIGHT, // Light theme. - direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. + colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT, // Light theme. + direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL, // Vertical direction. + screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; @@ -116,12 +117,13 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import abilityManager from '@ohos.app.ability.abilityManager'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; const config = { language: 'Zh-Hans', // Simplified Chinese. - colorMode: COLOR_MODE_LIGHT, // Light theme. - direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. + colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT, // Light theme. + direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL, // Vertical direction. + screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index c3d5a93c0f73f2b4e2e06caf8d1f45d9fd637f9f..f3e739c76ad25996ed767b71c0099ee7ca425abc 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -459,7 +459,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import appManager from '@ohos.app.ability.appManager'; -let observeId = 0; +let observerId = 0; // 1. Register an application state observer. let applicationStateObserver = { @@ -540,7 +540,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import appManager from '@ohos.app.ability.appManager'; -let observeId = 0; +let observerId = 0; // 1. Register an application state observer. let applicationStateObserver = { diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index 5a07867e6f5c28213e5cc48b07ef6a0958eb9426..d03dcb8185338c328e279df4b03849c434f1da6d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -72,9 +72,9 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { onCreate() { appRecovery.enableAppRecovery( - appRecovery.RestartFlag::ALWAYS_RESTART, - appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR, - appRecovery.SaveModeFlag::SAVE_WITH_FILE + appRecovery.RestartFlag.ALWAYS_RESTART, + appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR, + appRecovery.SaveModeFlag.SAVE_WITH_FILE ); } } @@ -105,7 +105,7 @@ let observer = { try { errorManager.on('error', observer); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -139,6 +139,6 @@ let observer = { try { errorManager.on('error', observer); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md index 989796d48ee22b34bd28b63b74fe20270d367577..49c3191c660f1848ffca26c13f8bebb2bfb754d0 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md @@ -127,6 +127,7 @@ Obtains the request callback from Want. ## RequestInfo Defines the request information, which is used as an input parameter for binding the modal dialog box. + **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index 96c67de7c5cc52b781f55add22b59859560ee9d5..53d009a28bb9be2f62a6dfee2540a7e0de184e39 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -35,7 +35,7 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; Called when the system memory level changes. -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** @@ -55,7 +55,7 @@ export default class MyAbility extends UIAbility { onCreate() { console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); - let EnvironmentCallback = { + let environmentCallback = { onConfigurationUpdated(config){ console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); } @@ -67,7 +67,7 @@ export default class MyAbility extends UIAbility { // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; // 2. Register a listener for the environment changes through the applicationContext object. - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + callbackId = applicationContext.registerEnvironmentCallback(environmentCallback); console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}'); } onDestroy() { diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 1224636ae4c0aa4ceb8634b244cd088257b64331..3304f535b5fd5fe52562e237a9f48c60cd794067 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -290,7 +290,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md))> | Yes| Callback used to return the mission information obtained.| + | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md)> | Yes| Callback used to return the mission information obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 74686becf7e0f2a20d5a3f8efb07071589296330..c041a599c6f9857db40e530f1e888c2a12f47f54 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -106,7 +106,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ## ServiceExtensionAbility.onConnect -onConnect(want: Want): rpc.RemoteObject; +onConnect(want: Want): rpc.RemoteObject | Promise; Called following **onCreate()** when a ServiceExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client. @@ -148,7 +148,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ## ServiceExtensionAbility.onDisconnect -onDisconnect(want: Want): void; +onDisconnect(want: Want): void | Promise; Called when a client is disconnected from this ServiceExtensionAbility. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index 54200ed3e7e27043eb2798522a3fd1c991eca5a3..b57435673e0d2372d4980c5a540fea618719c839 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -33,7 +33,7 @@ import StartOptions from '@ohos.app.ability.StartOptions'; try { missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } console.log('size = ${missions.length}'); @@ -49,6 +49,6 @@ import StartOptions from '@ohos.app.ability.StartOptions'; }); }); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index d840fd6854292aa876ecd3777e7cedc96b5e95bb..b85364df96d39f3b8bd66f64910f3e15e5867ca7 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -124,7 +124,7 @@ Called when the **WindowStage** is restored during the migration of this UIAbili ## UIAbility.onDestroy -onDestroy(): void; +onDestroy(): void | Promise<void>; Called when this UIAbility is destroyed to clear resources. @@ -181,7 +181,7 @@ Called when this UIAbility is switched from the foreground to the background. ## UIAbility.onContinue -onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; +onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResult; Called to save data during the ability migration preparation process. @@ -267,7 +267,7 @@ Dumps client information. ## UIAbility.onSaveState -onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; +onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult; Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. @@ -308,7 +308,7 @@ Implements sending of sequenceable data to the target ability when the CallerAbi ## Caller.call -call(method: string, data: rpc.Sequenceable): Promise<void>; +call(method: string, data: rpc.Parcelable): Promise<void>; Sends sequenceable data to the target ability. @@ -319,7 +319,7 @@ Sends sequenceable data to the target ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| -| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| +| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| **Return value** @@ -338,7 +338,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - class MyMessageAble{ // Custom sequenceable data structure. + class MyMessageAble{ // Custom parcelable data structure. name:'' str:'' num: 1 @@ -346,15 +346,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } @@ -369,7 +369,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error deviceId: '' }).then((obj) => { caller = obj; - let msg = new MyMessageAble('msg', 'world'); // See the definition of Sequenceable. + let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. caller.call(method, msg) .then(() => { console.log('Caller call() called'); @@ -387,7 +387,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ## Caller.callWithResult -callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; +callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence>; Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. @@ -398,13 +398,13 @@ Sends sequenceable data to the target ability and obtains the sequenceable data | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| -| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| +| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)> | Promise used to return the sequenceable data from the target ability.| +| Promise<[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)> | Promise used to return the sequenceable data from the target ability.| **Error codes** @@ -425,15 +425,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]'); return true; } @@ -453,7 +453,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error .then((data) => { console.log('Caller callWithResult() called'); let retmsg = new MyMessageAble(0, ''); - data.readSequenceable(retmsg); + data.readParcelable(retmsg); }) .catch((callErr) => { console.log('Caller.callWithResult catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}'); @@ -509,7 +509,7 @@ Releases the caller interface of the target ability. ## Caller.onRelease - onRelease(callback: OnReleaseCallBack): void; + onRelease(callback: OnReleaseCallback): void; Registers a callback that is invoked when the stub on the target ability is disconnected. @@ -519,7 +519,7 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| +| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| **Example** @@ -560,7 +560,7 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **release**.| -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| +| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| **Error codes** @@ -609,7 +609,7 @@ Deregisters a callback that is invoked when the stub on the target ability is di | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **release**.| -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| +| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| **Error codes** @@ -712,7 +712,7 @@ Registers a caller notification callback, which is invoked when the target abili | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | method | string | Yes| Notification message string negotiated between the two abilities.| -| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| +| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) type. The callback must return at least one empty [rpc.Parcelable](js-apis-rpc.md#parcelable9) object. Otherwise, the function execution fails.| **Error codes** @@ -733,15 +733,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } @@ -750,7 +750,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error function funcCallBack(pdata) { console.log('Callee funcCallBack is called ${pdata}'); let msg = new MyMessageAble('test', ''); - pdata.readSequenceable(msg); + pdata.readParcelable(msg); return new MyMessageAble('test1', 'Callee test'); } export default class MainUIAbility extends UIAbility { @@ -816,10 +816,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ## CalleeCallback -(indata: rpc.MessageParcel): rpc.Sequenceable; +(indata: rpc.MessageSequence): rpc.Parcelable; **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | Name| Readable| Writable| Type| Description| | -------- | -------- | -------- | -------- | -------- | -| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.| +| (indata: [rpc.MessageSequence](js-apis-rpc.md#messagesequence9)) | Yes| No| [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Prototype of the listener function registered by the callee.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index 0411725e055551e68d2902705f3e904592587a1d..a052c4dbec6fdb7c790c7195baf763f96dd90dad 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -136,7 +136,7 @@ import Want from '@ohos.app.ability.Want'; try { fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } catch(e) { - console.log('openSync fail: ${JSON.stringify(e)}'); + console.error('openSync fail: ${JSON.stringify(e)}'); } let want = { 'deviceId': '', // An empty deviceId indicates the local device. diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index fa8e44aa0b0e5a06d88891214baab112d0ce47b6..dbef711c25369d3eac61ca1b6516a7c43d8ecbc2 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -59,6 +59,6 @@ try { }; formBindingData.createFormBindingData(obj); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index 345f889f31e3d31cb834b03e9b5ecbde12aaabfe..7ea0a7024970cffde1434f76ce911cce28dbcd2e 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -273,7 +273,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ## onShareForm -onShareForm?(formId: string): { [key: string]: any } +onShareForm?(formId: string): { [key: string]: Object } Called by the widget provider to receive shared widget data. diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index e54e2cc798f8774fcc487d94c2ad9b514c42f897..bba49ff8ca2d8c96fd89e07b59c488d5cea12054 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -46,13 +46,13 @@ try { let formId = '12400633174999288'; formHost.deleteForm(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteForm success'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -96,10 +96,10 @@ try { formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -136,11 +136,11 @@ try { let formId = '12400633174999288'; formHost.releaseForm(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -178,11 +178,11 @@ try { let formId = '12400633174999288'; formHost.releaseForm(formId, true, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -226,10 +226,10 @@ try { formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -266,11 +266,11 @@ try { let formId = '12400633174999288'; formHost.requestForm(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -313,10 +313,10 @@ try { formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -354,11 +354,11 @@ try { let formId = '12400633174999288'; formHost.castToNormalForm(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -401,10 +401,10 @@ try { formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -441,11 +441,11 @@ try { let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -488,10 +488,10 @@ try { formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -528,11 +528,11 @@ try { let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -575,10 +575,10 @@ try { formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -615,11 +615,11 @@ try { let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -662,10 +662,10 @@ try { formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -702,11 +702,11 @@ try { let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -749,10 +749,10 @@ try { formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -778,11 +778,11 @@ import formHost from '@ohos.app.form.formHost'; try { formHost.isSystemReady((error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -809,10 +809,10 @@ try { formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -840,13 +840,13 @@ import formHost from '@ohos.app.form.formHost'; try { formHost.getAllFormsInfo((error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getAllFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -875,10 +875,10 @@ try { formHost.getAllFormsInfo().then((data) => { console.log('formHost getAllFormsInfo data: ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -914,13 +914,13 @@ import formHost from '@ohos.app.form.formHost'; try { formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -957,13 +957,13 @@ import formHost from '@ohos.app.form.formHost'; try { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1006,10 +1006,10 @@ try { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data) => { console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1039,13 +1039,13 @@ try { let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1081,10 +1081,10 @@ try { formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1130,13 +1130,13 @@ let want = { try { formHost.acquireFormState(want, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1188,10 +1188,10 @@ try { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1281,11 +1281,11 @@ let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsVisible(formIds, true, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1329,10 +1329,10 @@ try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1370,11 +1370,11 @@ let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsEnableUpdate(formIds, true, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1418,10 +1418,10 @@ try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` ## shareForm @@ -1459,11 +1459,11 @@ let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2 try { formHost.shareForm(formId, deviceId, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1508,10 +1508,10 @@ try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1549,11 +1549,11 @@ let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1595,9 +1595,9 @@ try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { console.log('formHost notifyFormsPrivacyProtected success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index 5815289bcf5258156932e938843bdb3d0ff4c441..908c5a428a1a5f6cccd3f5ae2bc04e01ffa29716 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -43,13 +43,13 @@ let formId = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider setFormNextRefreshTime success`); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -91,10 +91,10 @@ try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log(`formProvider setFormNextRefreshTime success`); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -132,13 +132,13 @@ try { let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.updateForm(formId, obj, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider updateForm success`); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -182,10 +182,10 @@ try { formProvider.updateForm(formId, obj).then(() => { console.log(`formProvider updateForm success`); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -219,13 +219,13 @@ import formProvider from '@ohos.app.form.formProvider'; try { formProvider.getFormsInfo((error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` ## getFormsInfo @@ -263,13 +263,13 @@ const filter: formInfo.FormInfoFilter = { try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -314,10 +314,10 @@ try { formProvider.getFormsInfo(filter).then((data) => { console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -364,13 +364,13 @@ try { let obj = formBindingData.createFormBindingData({ temperature: '22c', time: '22:00' }); formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -414,13 +414,13 @@ let want = { try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -471,10 +471,10 @@ try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is : ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -502,7 +502,7 @@ import formProvider from '@ohos.app.form.formProvider'; try { formProvider.isRequestPublishFormSupported((error, isSupported) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { if (isSupported) { var want = { @@ -516,19 +516,19 @@ try { try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } } } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -568,16 +568,16 @@ try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is : ${JSON.stringify(data)}'); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } } }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${error.code}, message: ${error.message})`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index 5edd8883d8f9d294f6f1408821efa95289108123..23bd66e43063c5e2ea38b65d38da68272b041adb 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -90,7 +90,7 @@ let config = { abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { - console.log('updateConfiguration fail'); + console.error('updateConfiguration fail'); }); ``` @@ -140,6 +140,6 @@ Obtains the ability running information. This API uses a promise to return the r abilityManager.getAbilityRunningInfos().then((data) => { console.log('getAbilityRunningInfos data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log('getAbilityRunningInfos err: ${JSON.stringify(err)}'); + console.error('getAbilityRunningInfos err: ${JSON.stringify(err)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index e9327b99666d40cb367e54ec351048af3d384cd3..7f03efce9a0fcec4585e4c3f7ebbb3d67a4fbe64 100644 --- a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -42,22 +42,22 @@ Enumerates gesture types. | Name | Description | | ------------- | ------------ | -| left | Left gesture. | -| leftThenRight | Left-then-right gesture.| -| leftThenUp | Left-then-up gesture.| -| leftThenDown | Left-then-down gesture.| -| right | Right gesture. | -| rightThenLeft | Right-then-left gesture.| -| rightThenUp | Right-then-up gesture.| -| rightThenDown | Right-then-down gesture.| -| up | Up gesture. | -| upThenLeft | Up-then-left gesture.| -| upThenRight | Up-then-right gesture.| -| upThenDown | Up-then-down gesture.| -| down | Down gesture. | -| downThenLeft | Down-then-left gesture.| -| downThenRight | Down-then-right gesture.| -| downThenUp | Down-then-up gesture.| +| left | Left gesture. String type. | +| leftThenRight | Left-then-right gesture. String type. | +| leftThenUp | Left-then-up gesture. String type. | +| leftThenDown | Left-then-down gesture. String type. | +| right | Right gesture. String type. | +| rightThenLeft | Right-then-left gesture. String type. | +| rightThenUp | Right-then-up gesture. String type. | +| rightThenDown | Right-then-down gesture. String type. | +| up | Up gesture. String type. | +| upThenLeft | Up-then-left gesture. String type. | +| upThenRight | Up-then-right gesture. String type. | +| upThenDown | Up-then-down gesture. String type. | +| down | Down gesture. String type. | +| downThenLeft | Down-then-left gesture. String type. | +| downThenRight | Down-then-right gesture. String type. | +| downThenUp | Down-then-up gesture. String type. | ## PageUpdateType @@ -67,8 +67,8 @@ Enumerates the page update types. | Name | Description | | ----------------- | --------- | -| pageContentUpdate | Update of the page content.| -| pageStateUpdate | Update of the page status.| +| pageContentUpdate | Update of the page content. String type. | +| pageStateUpdate | Update of the page status. String type. | ## TouchGuideType @@ -78,8 +78,8 @@ Enumerates the touch guide event types. | Name | Description | | ---------- | ------------ | -| touchBegin | Start of touch in touch guide mode.| -| touchEnd | End of touch in touch guide mode.| +| touchBegin | Start of touch in touch guide mode. String type. | +| touchEnd | End of touch in touch guide mode. String type. | ## AccessibilityExtensionAbility.onConnect diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index f32952bbbf73311db85ce014fbd4c8892f3b1d56..7b8e75b6bbc6d503f5f0d61409a77ff6d9374658 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -263,49 +263,6 @@ Registers an observer to listen for the state changes of all applications. console.log('-------- observerCode: ---------', observerCode); ``` -## appManager.registerApplicationStateObserver9+ - -registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; - -Registers an observer to listen for the state changes of a specified application. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| -| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| - -**Example** - - ```ts - let applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - }; - let bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - ``` ## appManager.unregisterApplicationStateObserver8+ unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 624d5946bdb8988dccc8709701d44ae1c9addd96..a8831b7f3b41a316356f6d7d660594414d5d3d10 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -33,11 +33,14 @@ export default class EntryAbility extends UIAbility { console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; + }, + onMemoryLevel(level){ + console.log('onMemoryLevel level: ${JSON.stringify(level)}'); } }; let applicationContext = this.context.getApplicationContext(); - applicationContext.registerEnvironmentCallback(envCallback); + applicationContext.on('environment',envCallback); windowStage.loadContent('pages/index', (err, data) => { if (err.code) { diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index ee7ba37cdd08795b0ea33e09dc687b7ccd4712bc..0a97689f23cdf69527c61dfc8dfba28e6869badf 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -81,7 +81,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { console.log('getRdbStore done, data : ${data}'); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { - console.log('executeSql done, error message : ${err}'); + console.error('executeSql done, error message : ${err}'); }); if (callback) { callback(); diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md index c7c5e55ff067afe25c43e57b0ce2491090324101..539d728f614c4c56655eb390e427febf63c16841 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -59,6 +59,6 @@ try { }; formBindingData.createFormBindingData(obj); } catch (error) { - console.log('catch error, error: ${JSON.stringify(error)}'); + console.error('catch error, error: ${JSON.stringify(error)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formProvider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md index 81b1711b18d198350e0ee6f759a7587b805cc66c..80f45e11e8d85b07f240b0f036aa4c86b2329b8a 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -36,7 +36,7 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback let formId = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error.code) { - console.log('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); + console.error('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); } }); ``` @@ -71,7 +71,7 @@ Sets the next refresh time for a widget. This API uses a promise to return the r formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); + console.error('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); }); ``` @@ -101,7 +101,7 @@ Updates a widget. This API uses an asynchronous callback to return the result. let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.updateForm(formId, obj, (error, data) => { if (error.code) { - console.log('formProvider updateForm, error: ${JSON.stringify(error)}'); + console.error('formProvider updateForm, error: ${JSON.stringify(error)}'); } }); ``` @@ -138,6 +138,6 @@ Updates a widget. This API uses a promise to return the result. formProvider.updateForm(formId, obj).then(() => { console.log('formProvider updateForm success'); }).catch((error) => { - console.log('formProvider updateForm, error: ${JSON.stringify(error)}'); + console.error('formProvider updateForm, error: ${JSON.stringify(error)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md index c09b0387f8aa1bff0b9f084136ad6ed70859c71f..97ea9181621dbc9b95d355762cb839af903771cc 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -382,97 +382,6 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r }); ``` -## missionManager.getLowResolutionMissionSnapShot9+ - -getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; - -Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.MANAGE_MISSIONS - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| - -**Example** - - ```ts - import missionManager from '@ohos.application.missionManager'; - - missionManager.getMissionInfos('', 10, (error, missions) => { - if (error.code) { - console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); - return; - } - console.log('size = ${missions.length}'); - console.log('missions = ${JSON.stringify(missions)}'); - let id = missions[0].missionId; - - missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => { - if (error.code) { - console.error('getLowResolutionMissionSnapShot failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); - return; - } - console.log('bundleName = ${snapshot.ability.bundleName}'); - }); - }); - ``` - - -## missionManager.getLowResolutionMissionSnapShot9+ - -getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; - -Obtains the low-resolution snapshot of a given mission. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.MANAGE_MISSIONS - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| - -**Example** - - ```ts - import missionManager from '@ohos.application.missionManager'; - - let allMissions; - missionManager.getMissionInfos('',10).then(function(res){ - allMissions=res; - }).catch(function(error) { - console.error('getMissionInfos fail, error: ${error}'); - }); - console.log('size = ${allMissions.length}'); - console.log('missions = ${JSON.stringify(allMissions)}'); - let id = allMissions[0].missionId; - - let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (error){ - console.error('getLowResolutionMissionSnapShot fail, error: ${error}'); - }); - ``` - - ## missionManager.lockMission lockMission(missionId: number, callback: AsyncCallback<void>): void; diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index d5fd64638541acdb567b3d2a04d4bf5933c822f1..7844ed3008796cf449c32d09c246af86b65338d8 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -25,9 +25,8 @@ import Want from '@ohos.application.Want'; | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| | action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | | entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | -| moduleName9+ | string | No | Module to which the ability belongs.| **Example** @@ -42,7 +41,7 @@ import Want from '@ohos.application.Want'; }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log('error.code = ${error.code}'); + console.error('error.code = ${error.code}'); }); ``` @@ -114,7 +113,7 @@ import Want from '@ohos.application.Want'; try { fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } catch(e) { - console.log('openSync fail: ${JSON.stringify(e)}'); + console.error('openSync fail: ${JSON.stringify(e)}'); } let want = { 'deviceId': '', // An empty deviceId indicates the local device. @@ -127,7 +126,7 @@ import Want from '@ohos.application.Want'; }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log('error.code = ${error.code}'); + console.error('error.code = ${error.code}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 4abed77e24d5c6cf16d7fd84ce36cf806d06ce4e..b3f5def410251e954ee3f7b00c211e2f7f5116a0 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -23,9 +23,9 @@ import audio from '@ohos.multimedia.audio'; | Name | Type | Readable | Writable| Description | | --------------------------------------- | ----------| ---- | ---- | ------------------ | -| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | -| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | -| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | **Example** @@ -1763,7 +1763,7 @@ Sets a device to the active state. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | | active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| @@ -1795,7 +1795,7 @@ Sets a device to the active state. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type.| | active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** @@ -1829,7 +1829,7 @@ Checks whether a device is active. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** @@ -1860,7 +1860,7 @@ Checks whether a device is active. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type.| **Return value** @@ -3956,6 +3956,7 @@ Describes the audio renderer change event. **Example** ```js + import audio from '@ohos.multimedia.audio'; const audioManager = audio.getAudioManager(); @@ -4240,7 +4241,6 @@ audioRenderer.getStreamInfo().then((streamInfo) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getAudioStreamId9+ @@ -4263,7 +4263,6 @@ Obtains the stream ID of this **AudioRenderer** instance. This API uses an async audioRenderer.getAudioStreamId((err, streamid) => { console.info(`Renderer GetStreamId: ${streamid}`); }); - ``` ### getAudioStreamId9+ @@ -4288,7 +4287,6 @@ audioRenderer.getAudioStreamId().then((streamid) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### start8+ @@ -4315,7 +4313,6 @@ audioRenderer.start((err) => { console.info('Renderer start success.'); } }); - ``` ### start8+ @@ -4340,7 +4337,6 @@ audioRenderer.start().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### pause8+ @@ -4367,7 +4363,6 @@ audioRenderer.pause((err) => { console.info('Renderer paused.'); } }); - ``` ### pause8+ @@ -4392,7 +4387,6 @@ audioRenderer.pause().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### drain8+ @@ -4419,7 +4413,6 @@ audioRenderer.drain((err) => { console.info('Renderer drained.'); } }); - ``` ### drain8+ @@ -4444,7 +4437,6 @@ audioRenderer.drain().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### stop8+ @@ -4471,7 +4463,6 @@ audioRenderer.stop((err) => { console.info('Renderer stopped.'); } }); - ``` ### stop8+ @@ -4496,7 +4487,6 @@ audioRenderer.stop().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### release8+ @@ -4523,7 +4513,6 @@ audioRenderer.release((err) => { console.info('Renderer released.'); } }); - ``` ### release8+ @@ -4548,7 +4537,6 @@ audioRenderer.release().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### write8+ @@ -4586,15 +4574,15 @@ let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let stat = await fs.stat(path); let buf = new ArrayBuffer(bufferSize); -let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); +let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); for (let i = 0;i < len; i++) { let options = { - offset: i * this.bufferSize, - length: this.bufferSize + offset: i * bufferSize, + length: bufferSize } let readsize = await fs.read(file.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer.write(buf,(err,writeSize)=>{ + audioRenderer.write(buf,(err,writeSize)=>{ if(err){ reject(err) }else{ @@ -4604,7 +4592,6 @@ for (let i = 0;i < len; i++) { }) } - ``` ### write8+ @@ -4641,20 +4628,19 @@ let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let stat = await fs.stat(path); let buf = new ArrayBuffer(bufferSize); -let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); +let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); for (let i = 0;i < len; i++) { let options = { - offset: i * this.bufferSize, - length: this.bufferSize + offset: i * bufferSize, + length: bufferSize } let readsize = await fs.read(file.fd, buf, options) try{ - let writeSize = await this.audioRenderer.write(buf); + let writeSize = await audioRenderer.write(buf); } catch(err) { console.error(`audioRenderer.write err: ${err}`); } } - ``` ### getAudioTime8+ @@ -4677,7 +4663,6 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); - ``` ### getAudioTime8+ @@ -4702,7 +4687,6 @@ audioRenderer.getAudioTime().then((timestamp) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getBufferSize8+ @@ -4727,7 +4711,6 @@ let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { console.error('getBufferSize error'); } }); - ``` ### getBufferSize8+ @@ -4754,7 +4737,6 @@ audioRenderer.getBufferSize().then((data) => { }).catch((err) => { console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); - ``` ### setRenderRate8+ @@ -4782,7 +4764,6 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => console.info('Callback invoked to indicate a successful render rate setting.'); } }); - ``` ### setRenderRate8+ @@ -4813,7 +4794,6 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getRenderRate8+ @@ -4836,7 +4816,6 @@ Obtains the current render rate. This API uses an asynchronous callback to retur audioRenderer.getRenderRate((err, renderrate) => { console.info(`getRenderRate: ${renderrate}`); }); - ``` ### getRenderRate8+ @@ -4861,9 +4840,7 @@ audioRenderer.getRenderRate().then((renderRate) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` - ### setInterruptMode9+ setInterruptMode(mode: InterruptMode): Promise<void> @@ -4893,9 +4870,7 @@ audioRenderer.setInterruptMode(mode).then(data=>{ }).catch((err) => { console.error(`setInterruptMode Fail: ${err}`); }); - ``` - ### setInterruptMode9+ setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void @@ -4921,7 +4896,6 @@ audioRenderer.setInterruptMode(mode, (err, data)=>{ } console.info('setInterruptMode Success!'); }); - ``` ### setVolume9+ @@ -4952,9 +4926,7 @@ audioRenderer.setVolume(0.5).then(data=>{ }).catch((err) => { console.error(`setVolume Fail: ${err}`); }); - ``` - ### setVolume9+ setVolume(volume: number, callback: AsyncCallback\): void @@ -4979,7 +4951,6 @@ audioRenderer.setVolume(0.5, (err, data)=>{ } console.info('setVolume Success!'); }); - ``` ### on('audioInterrupt')9+ @@ -5005,7 +4976,7 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco | ID | Error Message | | ------- | ------------------------------ | -| 6800101 | if input parameter value error | +| 6800101 | if input parameter value error | **Example** @@ -5059,7 +5030,6 @@ async function onAudioInterrupt(){ } }); } - ``` ### on('markReach')8+ @@ -5086,7 +5056,6 @@ audioRenderer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` @@ -5108,7 +5077,6 @@ Unsubscribes from mark reached events. ```js audioRenderer.off('markReach'); - ``` ### on('periodReach') 8+ @@ -5135,7 +5103,6 @@ audioRenderer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('periodReach') 8+ @@ -5156,10 +5123,9 @@ Unsubscribes from period reached events. ```js audioRenderer.off('periodReach') - ``` -### on('stateChange')8+ +### on('stateChange') 8+ on(type: 'stateChange', callback: Callback): void @@ -5185,7 +5151,6 @@ audioRenderer.on('stateChange', (state) => { console.info('audio renderer state is: STATE_RUNNING'); } }); - ``` ## AudioCapturer8+ @@ -5204,7 +5169,6 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo ```js let state = audioCapturer.state; - ``` ### getCapturerInfo8+ @@ -5233,7 +5197,6 @@ audioCapturer.getCapturerInfo((err, capturerInfo) => { console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); - ``` @@ -5266,7 +5229,6 @@ audioCapturer.getCapturerInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); - ``` ### getStreamInfo8+ @@ -5297,7 +5259,6 @@ audioCapturer.getStreamInfo((err, streamInfo) => { console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); - ``` ### getStreamInfo8+ @@ -5326,7 +5287,6 @@ audioCapturer.getStreamInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`getStreamInfo :ERROR: ${err}`); }); - ``` ### getAudioStreamId9+ @@ -5349,7 +5309,6 @@ Obtains the stream ID of this **AudioCapturer** instance. This API uses an async audioCapturer.getAudioStreamId((err, streamid) => { console.info(`audioCapturer GetStreamId: ${streamid}`); }); - ``` ### getAudioStreamId9+ @@ -5374,7 +5333,6 @@ audioCapturer.getAudioStreamId().then((streamid) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### start8+ @@ -5401,7 +5359,6 @@ audioCapturer.start((err) => { console.info('Capturer start success.'); } }); - ``` @@ -5433,7 +5390,6 @@ audioCapturer.start().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); - ``` ### stop8+ @@ -5460,7 +5416,6 @@ audioCapturer.stop((err) => { console.info('Capturer stopped.'); } }); - ``` @@ -5490,7 +5445,6 @@ audioCapturer.stop().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); - ``` ### release8+ @@ -5517,7 +5471,6 @@ audioCapturer.release((err) => { console.info('capturer released.'); } }); - ``` @@ -5547,7 +5500,6 @@ audioCapturer.release().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); - ``` ### read8+ @@ -5581,7 +5533,6 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => { console.info('Success in reading the buffer data'); } }); - ``` ### read8+ @@ -5621,7 +5572,6 @@ audioCapturer.read(bufferSize, true).then((buffer) => { }).catch((err) => { console.info(`ERROR : ${err}`); }); - ``` ### getAudioTime8+ @@ -5644,7 +5594,6 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioCapturer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); - ``` ### getAudioTime8+ @@ -5669,7 +5618,6 @@ audioCapturer.getAudioTime().then((audioTime) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); - ``` ### getBufferSize8+ @@ -5699,7 +5647,6 @@ audioCapturer.getBufferSize((err, bufferSize) => { }); } }); - ``` ### getBufferSize8+ @@ -5726,7 +5673,6 @@ audioCapturer.getBufferSize().then((data) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); - ``` ### on('markReach')8+ @@ -5753,7 +5699,6 @@ audioCapturer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('markReach')8+ @@ -5774,7 +5719,6 @@ Unsubscribes from mark reached events. ```js audioCapturer.off('markReach'); - ``` ### on('periodReach')8+ @@ -5801,7 +5745,6 @@ audioCapturer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('periodReach')8+ @@ -5822,10 +5765,9 @@ Unsubscribes from period reached events. ```js audioCapturer.off('periodReach') - ``` -### on('stateChange')8+ +### on('stateChange') 8+ on(type: 'stateChange', callback: Callback): void @@ -5851,7 +5793,6 @@ audioCapturer.on('stateChange', (state) => { console.info('audio capturer state is: STATE_RUNNING'); } }); - ``` ## ToneType9+ @@ -5926,7 +5867,6 @@ tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { console.info('callback call load success'); } }); - ``` ### load9+ @@ -5959,7 +5899,6 @@ tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { }).catch(() => { console.error('promise call load fail'); }); - ``` ### start9+ @@ -5989,7 +5928,6 @@ tonePlayer.start((err) => { console.info('callback call start success'); } }); - ``` ### start9+ @@ -6016,7 +5954,6 @@ tonePlayer.start().then(() => { }).catch(() => { console.error('promise call start fail'); }); - ``` ### stop9+ @@ -6046,7 +5983,6 @@ tonePlayer.stop((err) => { console.error('callback call stop success '); } }); - ``` ### stop9+ @@ -6073,7 +6009,6 @@ tonePlayer.stop().then(() => { }).catch(() => { console.error('promise call stop fail'); }); - ``` ### release9+ @@ -6103,7 +6038,6 @@ tonePlayer.release((err) => { console.info('callback call release success '); } }); - ``` ### release9+ @@ -6130,7 +6064,6 @@ tonePlayer.release().then(() => { }).catch(() => { console.error('promise call release fail'); }); - ``` ## ActiveDeviceType(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 86fc2ceeebebd248a2e51f6454ea74dbc2f80602..b89eb42bc8793b9d28f1682ab87b1ac9f157c14d 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -2,7 +2,7 @@ The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller. -This module provides the following common features related to media sessions: +This module provides the following typical features related to media sessions: - [AVSession](#avsession): used to set session metadata, playback state information, and more. - [AVSessionController](#avsessioncontroller): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. @@ -26,6 +26,8 @@ Creates a media session. This API uses a promise to return the result. An abilit **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -41,8 +43,8 @@ Creates a media session. This API uses a promise to return the result. An abilit | --------------------------------- | ------------------------------------------------------------ | | Promise<[AVSession](#avsession)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| - **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -74,6 +76,8 @@ Creates a media session. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -84,6 +88,7 @@ Creates a media session. This API uses an asynchronous callback to return the re | callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -128,6 +133,7 @@ Obtains the descriptors of all sessions. This API uses a promise to return the r | Promise\\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -155,7 +161,7 @@ getAllSessionDescriptors(callback: AsyncCallback\\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -191,6 +198,101 @@ avSession.getAllSessionDescriptors(function (err, descriptors) { }); ``` +## avSession.getHistoricalSessionDescriptors10+ + +getHistoricalSessionDescriptors(maxSize?: number): Promise\>> + +Obtains the descriptors of all sessions. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES + +**System capability**: SystemCapability.Multimedia.AVSession.Manager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -----------------------------------------------------------------| +| maxSize | number | No | Maximum number of descriptors to obtain. The value ranges from 0 to 10. If this parameter is left blank, the default value **3** is used.| + +**Return value** + +| Type | Description | +| --------------------------------------------------------------------------- | -------------------------------------- | +| Promise\\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | + +**Example** + +```js +avSession.getHistoricalSessionDescriptors().then((descriptors) => { + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); + if(descriptors.length > 0 ){ + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); + } +}).catch((err) => { + console.info(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +## avSession.getHistoricalSessionDescriptors10+ + +getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\>>): void + +Obtains the descriptors of all sessions. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES + +**System capability**: SystemCapability.Multimedia.AVSession.Manager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------------------------ | ---- | -----------------------------------------------------------------| +| maxSize | number | Yes | Maximum number of descriptors to obtain. The value ranges from 0 to 10. If this parameter is left blank, the default value **3** is used.| +| callback | AsyncCallback\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 |Session service exception. | + +**Example** + +```js +avSession.getHistoricalSessionDescriptors(1, function (err, descriptors) { + if (err) { + console.info(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); + if(descriptors.length > 0 ){ + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); + } + } +}); +``` + ## avSession.createController createController(sessionId: string): Promise\ @@ -216,6 +318,7 @@ Creates a session controller based on the session ID. Multiple session controlle | Promise<[AVSessionController](#avsessioncontroller)\> | Promise used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -268,6 +371,7 @@ Creates a session controller based on the session ID. Multiple session controlle | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -327,9 +431,10 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the cast is successful, no value is returned; otherwise, an error object is returned.| +| Promise | Promise used to return the result. If the casting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -382,6 +487,7 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | callback | AsyncCallback | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -433,6 +539,7 @@ Subscribes to session creation, session destruction, and top session change even | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes | Callback used to report the session descriptor. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -478,9 +585,10 @@ Unsubscribes from session creation, session destruction, and top session change | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type.
- **'sessionCreate'**: session creation event, which is reported when a session is created.
- **'sessionDestroy'**: session destruction event, which is reported when a session is destroyed.
- **'topSessionChange'**: top session change event, which is reported when the top session is changed.| -| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **session** parameter in the callback describes a media session. The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **session** parameter in the callback describes a media session. The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -503,6 +611,8 @@ Subscribes to session service death events. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -511,6 +621,7 @@ Subscribes to session service death events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -533,14 +644,17 @@ Unsubscribes from session service death events. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | | ------ | ---------------------- | ---- | ------------------------------------------------------- | | type | string | Yes | Event type. The event **'sessionServiceDie'** is reported when the session service dies.| -| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -578,6 +692,7 @@ Sends a system key event to the top session. This API uses a promise to return t | Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -620,6 +735,7 @@ Sends a system key event to the top session. This API uses an asynchronous callb | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -667,6 +783,7 @@ Sends a system control command to the top session. This API uses a promise to re | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -721,6 +838,7 @@ Sends a system control command to the top session. This API uses an asynchronous | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -765,6 +883,8 @@ An **AVSession** object is created by calling [avSession.createAVSession](#avses **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Readable| Writable| Description | | :-------- | :----- | :--- | :--- | :---------------------------- | @@ -784,6 +904,8 @@ Sets session metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -797,6 +919,7 @@ Sets session metadata. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -838,6 +961,8 @@ Sets session metadata. This API uses an asynchronous callback to return the resu **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -846,6 +971,7 @@ Sets session metadata. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -889,6 +1015,8 @@ Sets information related to the session playback state. This API uses a promise **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -902,6 +1030,7 @@ Sets information related to the session playback state. This API uses a promise | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -935,6 +1064,8 @@ Sets information related to the session playback state. This API uses an asynchr **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -943,6 +1074,7 @@ Sets information related to the session playback state. This API uses an asynchr | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -970,6 +1102,220 @@ session.setAVPlaybackState(PlaybackState, function (err) { }); ``` +### setAVQueueItems10+ + +setAVQueueItems(items: Array\): Promise + +Sets a playlist. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ---------------------------------- | +| items | Array<[AVQueueItem](#avqueueitem10)\> | Yes | Playlist to set.| + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueItemDescription_1 = { + mediaId: '001', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_1 = { + itemId: 1, + description: queueItemDescription_1 +}; +let queueItemDescription_2 = { + mediaId: '002', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_2 = { + itemId: 2, + description: queueItemDescription_2 +}; +let queueItemsArray = [queueItem_1, queueItem_2]; +session.setAVQueueItems(queueItemsArray).then(() => { + console.info('SetAVQueueItems successfully'); +}).catch((err) => { + console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### setAVQueueItems10+ + +setAVQueueItems(items: Array\, callback: AsyncCallback): void + +Sets a playlist. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ----------------------------------------------------------- | +| items | Array<[AVQueueItem](#avqueueitem10)\> | Yes | Playlist to set. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueItemDescription_1 = { + mediaId: '001', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_1 = { + itemId: 1, + description: queueItemDescription_1 +}; +let queueItemDescription_2 = { + mediaId: '002', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_2 = { + itemId: 2, + description: queueItemDescription_2 +}; +let queueItemsArray = [queueItem_1, queueItem_2]; +session.setAVQueueItems(queueItemsArray, function (err) { + if (err) { + console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SetAVQueueItems successfully'); + } +}); +``` + +### setAVQueueTitle10+ + +setAVQueueTitle(title: string): Promise\ + +Sets a name for the playlist. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| title | string | Yes | Name of the playlist.| + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueTitle = 'QUEUE_TITLE'; +session.setAVQueueTitle(queueTitle).then(() => { + console.info('SetAVQueueTitle successfully'); +}).catch((err) => { + console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### setAVQueueTitle10+ + +setAVQueueTitle(title: string, callback: AsyncCallback\): void + +Sets a name for the playlist. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| title | string | Yes | Name of the playlist. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueTitle = 'QUEUE_TITLE'; +session.setAVQueueTitle(queueTitle, function (err) { + if (err) { + console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SetAVQueueTitle successfully'); + } +}); +``` + ### setLaunchAbility setLaunchAbility(ability: WantAgent): Promise\ @@ -978,6 +1324,8 @@ Sets a launcher ability. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -991,6 +1339,7 @@ Sets a launcher ability. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1048,6 +1397,8 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1056,6 +1407,7 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1107,21 +1459,31 @@ wantAgent.getWantAgent(wantAgentInfo).then((agent) => { }); ``` -### getController +### dispatchSessionEvent10+ -getController(): Promise\ +dispatchSessionEvent(event: string, args: {[key: string]: Object}): Promise\ -Obtains the controller corresponding to this session. This API uses a promise to return the result. +Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| event | string | Yes | Name of the session event.| +| args | {[key: string]: any} | Yes | Event content in key-value pair format.| + **Return value** -| Type | Description | -| ---------------------------------------------------- | ----------------------------- | -| Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.| +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1132,7 +1494,85 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -let controller; +let eventName = "dynamic_lyric"; +let args = { + lyric : "This is lyric" +} +await session.dispatchSessionEvent(eventName, args).catch((err) => { + console.info(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); +}) +``` + +### dispatchSessionEvent10+ + +dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback): void + +Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| event | string | Yes | Name of the session event.| +| args | {[key: string]: any} | Yes | Event content in key-value pair format.| +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let eventName = "dynamic_lyric"; +let args = { + lyric : "This is lyric" +} +await session.dispatchSessionEvent(eventName, args, (err) => { + if(err) { + console.info(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); + } +}) +``` + +### getController + +getController(): Promise\ + +Obtains the controller corresponding to this session. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ----------------------------- | +| Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let controller; session.getController().then((avcontroller) => { controller = avcontroller; console.info(`GetController : SUCCESS : sessionid : ${controller.sessionId}`); @@ -1149,6 +1589,8 @@ Obtains the controller corresponding to this session. This API uses an asynchron **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1156,6 +1598,7 @@ Obtains the controller corresponding to this session. This API uses an asynchron | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1185,6 +1628,8 @@ Obtains information about the output device for this session. This API uses a pr **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -1192,6 +1637,7 @@ Obtains information about the output device for this session. This API uses a pr | Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise used to return the output device information.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1217,6 +1663,8 @@ Obtains information about the output device for this session. This API uses an a **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1224,6 +1672,7 @@ Obtains information about the output device for this session. This API uses an a | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1251,6 +1700,8 @@ Activates this session. A session can be used only after being activated. This A **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -1258,6 +1709,7 @@ Activates this session. A session can be used only after being activated. This A | Promise | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1283,6 +1735,8 @@ Activates this session. A session can be used only after being activated. This A **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1290,6 +1744,7 @@ Activates this session. A session can be used only after being activated. This A | callback | AsyncCallback | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1317,6 +1772,8 @@ Deactivates this session. You can use [activate](#activate) to activate the sess **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -1324,6 +1781,7 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Promise | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1351,6 +1809,8 @@ Deactivates this session. You can use [activate](#activate) to activate the sess **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1358,6 +1818,7 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | callback | AsyncCallback | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1385,6 +1846,8 @@ Destroys this session. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -1392,6 +1855,7 @@ Destroys this session. This API uses a promise to return the result. | Promise | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1415,9 +1879,10 @@ destroy(callback: AsyncCallback\): void Destroys this session. This API uses an asynchronous callback to return the result. - **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1425,6 +1890,7 @@ Destroys this session. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1452,6 +1918,8 @@ Subscribes to playback command events. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1460,6 +1928,7 @@ Subscribes to playback command events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1501,6 +1970,8 @@ Subscribes to the seek event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1509,6 +1980,7 @@ Subscribes to the seek event. | callback | (time: number) => void | Yes | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1532,6 +2004,8 @@ Subscribes to the event for setting the playback speed. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1540,6 +2014,7 @@ Subscribes to the event for setting the playback speed. | callback | (speed: number) => void | Yes | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1563,6 +2038,8 @@ Subscribes to the event for setting the loop mode. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1571,6 +2048,7 @@ Subscribes to the event for setting the loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | Yes | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1594,6 +2072,8 @@ Subscribes to the event for favoriting a media asset. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1602,6 +2082,7 @@ Subscribes to the event for favoriting a media asset. | callback | (assetId: string) => void | Yes | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1617,6 +2098,40 @@ session.on('toggleFavorite', (assetId) => { }); ``` +### on('skipToQueueItem')10+ + +on(type: 'skipToQueueItem', callback: (itemId: number) => void): void + +Subscribes to the event that indicates an item in the playlist is selected. The session can play the selected item. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The event **'skipToQueueItem'** is reported when the command for selecting an item in the playlist is sent to the session.| +| callback | (itemId: number) => void | Yes | Callback used for subscription. The **itemId** parameter in the callback indicates the ID of the selected item. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +session.on('skipToQueueItem', (itemId) => { + console.info(`on skipToQueueItem id : ${itemId}`); +}); +``` + ### on('handleKeyEvent') on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void @@ -1625,6 +2140,8 @@ Subscribes to the key event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1633,6 +2150,7 @@ Subscribes to the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes | Callback used for subscription. The **event** parameter in the callback indicates the key event. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1656,6 +2174,8 @@ Subscribes to output device changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1664,6 +2184,7 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1679,6 +2200,40 @@ session.on('outputDeviceChange', (device) => { }); ``` +### on('commonCommand')10+ + +on(type: 'commonCommand', callback: (command: string, args: {[key: string]: Object}) => void): void + +Subscribes to custom control command changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The event **'commonCommand'** is reported when a custom control command changes.| +| callback | (commonCommand: string, args: {[key:string]: Object}) => void | Yes | Callback used for subscription. The **commonCommand** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**Example** + +```js +session.on('commonCommand', (commonCommand, args) => { + console.info(`OnCommonCommand, the command is ${commonCommand}, args: ${JSON.stringify(args)}`); +}); +``` + ### off('play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind') off(type: 'play' | 'pause' | 'stop' | 'playNext' | 'playPrevious' | 'fastForward' | 'rewind', callback?: () => void): void @@ -1687,14 +2242,17 @@ Unsubscribes from playback command events. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | | type | string | Yes | Event type. The following events are supported: **'play'**, **'pause'**, **'stop'**, **'playNext'**, **'playPrevious'**, **'fastForward'**, and **'rewind'**.| -| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1722,14 +2280,17 @@ Unsubscribes from the seek event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ----------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'seek'**. | -| callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1751,14 +2312,17 @@ Unsubscribes from the event for setting the playback speed. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------------| | type | string | Yes | Event type. The value is fixed at **'setSpeed'**. | -| callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1780,14 +2344,17 @@ Unsubscribes from the event for setting loop mode. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ----- | | type | string | Yes | Event type. The value is fixed at **'setLoopMode'**.| -| callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions.| +| callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1809,14 +2376,17 @@ Unsubscribes from the event for favoriting a media asset. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'toggleFavorite'**. | -| callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1830,6 +2400,38 @@ For details about the error codes, see [AVSession Management Error Codes](../err session.off('toggleFavorite'); ``` +### off('skipToQueueItem')10+ + +off(type: 'skipToQueueItem', callback?: (itemId: number) => void): void + +Unsubscribes from the event that indicates an item in the playlist is selected. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'skipToQueueItem'**. | +| callback | (itemId: number) => void | No | Callback used for unsubscription. The **itemId** parameter in the callback indicates the ID of the item.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +session.off('skipToQueueItem'); +``` + ### off('handleKeyEvent') off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void @@ -1838,14 +2440,17 @@ Unsubscribes from the key event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'handleKeyEvent'**. | -| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1867,14 +2472,17 @@ Unsubscribes from playback device changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'outputDeviceChange'**. | -| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1889,6 +2497,38 @@ session.off('outputDeviceChange'); ``` +### off('commonCommand')10+ + +off(type: 'commonCommand', callback?: (commonCommand: string, args: {[key:string]: Object}) => void): void + +Unsubscribes from custom control command changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'commonCommand'**. | +| callback | (commonCommand: string, args: {[key:string]: Object}) => void | No | Callback used for unsubscription. The **commonCommand** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**Example** + +```js +session.off('commonCommand'); +``` + + ## AVSessionController @@ -1922,6 +2562,8 @@ Obtains the information related to the playback state. This API uses a promise t **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -1929,6 +2571,7 @@ Obtains the information related to the playback state. This API uses a promise t | Promise<[AVPlaybackState](#avplaybackstate)\> | Promise used to return the **AVPlaybackState** object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1954,6 +2597,8 @@ Obtains the information related to the playback state. This API uses an asynchro **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1961,6 +2606,7 @@ Obtains the information related to the playback state. This API uses an asynchro | callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | Yes | Callback used to return the **AVPlaybackState** object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1980,21 +2626,24 @@ controller.getAVPlaybackState(function (err, playbackState) { }); ``` -### getAVMetadata +### getAVQueueItems10+ -getAVMetadata(): Promise\ +getAVQueueItems(): Promise\> -Obtains the session metadata. This API uses a promise to return the result. +Obtains the information related to the items in the queue. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | -| Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.| +| Type | Description | +| --------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the items in the queue.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2005,21 +2654,248 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -controller.getAVMetadata().then((metadata) => { - console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`); +controller.getAVQueueItems().then((items) => { + console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`); }).catch((err) => { - console.info(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); + console.info(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); }); ``` -### getAVMetadata +### getAVQueueItems10+ -getAVMetadata(callback: AsyncCallback\): void +getAVQueueItems(callback: AsyncCallback\>): void -Obtains the session metadata. This API uses an asynchronous callback to return the result. +Obtains the information related to the items in the playlist. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the items in the playlist.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +controller.getAVQueueItems(function (err, items) { + if (err) { + console.info(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`); + } +}); +``` + +### getAVQueueTitle10+ + +getAVQueueTitle(): Promise\ + +Obtains the name of the playlist. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------- | +| Promise | Promise used to return the playlist name.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +controller.getAVQueueTitle().then((title) => { + console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`); +}).catch((err) => { + console.info(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### getAVQueueTitle10+ + +getAVQueueTitle(callback: AsyncCallback\): void + +Obtains the name of the playlist. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the playlist name.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +controller.getAVQueueTitle(function (err, title) { + if (err) { + console.info(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`); + } +}); +``` + +### skipToQueueItem10+ + +skipToQueueItem(itemId: number): Promise\ + +Sends the ID of an item in the playlist to the session for processing. The session can play the song. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------- | +| itemId | number | Yes | ID of an item in the playlist.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------------------------------------------- | +| Promise | Promise used to return the result. If the item ID is sent, no value is returned; otherwise, an error object is returned.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueItemId = 0; +controller.skipToQueueItem(queueItemId).then(() => { + console.info('SkipToQueueItem successfully'); +}).catch((err) => { + console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### skipToQueueItem10+ + +skipToQueueItem(itemId: number, callback: AsyncCallback\): void + +Sends the ID of an item in the playlist to the session for processing. The session can play the song. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| itemId | number | Yes | ID of an item in the playlist. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let queueItemId = 0; +controller.skipToQueueItem(queueItemId, function (err) { + if (err) { + console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SkipToQueueItem successfully'); + } +}); +``` + +### getAVMetadata + +getAVMetadata(): Promise\ + +Obtains the session metadata. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +controller.getAVMetadata().then((metadata) => { + console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`); +}).catch((err) => { + console.info(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### getAVMetadata + +getAVMetadata(callback: AsyncCallback\): void + +Obtains the session metadata. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2027,6 +2903,7 @@ Obtains the session metadata. This API uses an asynchronous callback to return t | callback | AsyncCallback<[AVMetadata](#avmetadata)\> | Yes | Callback used to return the metadata obtained.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2054,6 +2931,8 @@ Obtains the output device information. This API uses a promise to return the res **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2061,6 +2940,7 @@ Obtains the output device information. This API uses a promise to return the res | Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise used to return the information obtained.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2085,6 +2965,8 @@ Obtains the output device information. This API uses an asynchronous callback to **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2092,6 +2974,7 @@ Obtains the output device information. This API uses an asynchronous callback to | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2119,6 +3002,8 @@ Sends a key event to the session corresponding to this controller. This API uses **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -2126,6 +3011,7 @@ Sends a key event to the session corresponding to this controller. This API uses | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2163,6 +3049,8 @@ Sends a key event to the session corresponding to this controller. This API uses **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2171,6 +3059,7 @@ Sends a key event to the session corresponding to this controller. This API uses | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2204,6 +3093,8 @@ Obtains the **WantAgent** object saved by the application in the session. This A **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2211,6 +3102,7 @@ Obtains the **WantAgent** object saved by the application in the session. This A | Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2239,6 +3131,8 @@ Obtains the **WantAgent** object saved by the application in the session. This A **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2246,6 +3140,7 @@ Obtains the **WantAgent** object saved by the application in the session. This A | callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2276,6 +3171,8 @@ Obtains the playback position. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2283,6 +3180,7 @@ Obtains the playback position. | number | Playback position, in milliseconds.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2304,6 +3202,8 @@ Checks whether the session is activated. This API uses a promise to return the r **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2311,6 +3211,7 @@ Checks whether the session is activated. This API uses a promise to return the r | Promise | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2337,6 +3238,8 @@ Checks whether the session is activated. This API uses an asynchronous callback **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2344,6 +3247,7 @@ Checks whether the session is activated. This API uses an asynchronous callback | callback | AsyncCallback | Yes | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2372,6 +3276,8 @@ Destroys this controller. A controller can no longer be used after being destroy **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2379,6 +3285,7 @@ Destroys this controller. A controller can no longer be used after being destroy | Promise | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2404,6 +3311,8 @@ Destroys this controller. A controller can no longer be used after being destroy **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2411,6 +3320,7 @@ Destroys this controller. A controller can no longer be used after being destroy | callback | AsyncCallback | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2438,6 +3348,8 @@ Obtains valid commands supported by the session. This API uses a promise to retu **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Return value** | Type | Description | @@ -2445,6 +3357,7 @@ Obtains valid commands supported by the session. This API uses a promise to retu | Promise\> | Promise used to return a set of valid commands.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2471,6 +3384,8 @@ Obtains valid commands supported by the session. This API uses an asynchronous c **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2478,6 +3393,7 @@ Obtains valid commands supported by the session. This API uses an asynchronous c | callback | AsyncCallback\\> | Yes | Callback used to return a set of valid commands.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2506,6 +3422,8 @@ Sends a control command to the session through the controller. This API uses a p **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2519,6 +3437,7 @@ Sends a control command to the session through the controller. This API uses a p | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2559,6 +3478,8 @@ Sends a control command to the session through the controller. This API uses an **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2567,6 +3488,7 @@ Sends a control command to the session through the controller. This API uses an | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2601,6 +3523,95 @@ controller.sendControlCommand(avCommand, function (err) { }); ``` +### sendCommonCommand10+ + +sendCommonCommand(command: string, args: {[key: string]: Object}): Promise\ + +Sends a custom control command to the session through the controller. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------------------------ | +| command | string | Yes | Name of the custom control command.| +| args | {[key: string]: any} | Yes | Parameters in key-value pair format carried in the custom control command.| + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | + +**Example** + +```js +let commandName = "my_command"; +let args = { + command : "This is my command" +} +await controller.sendCommonCommand(commandName, args).catch((err) => { + console.info(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`); +}) +``` + +### sendCommonCommand10+ + +sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback\): void + +Sends a custom control command to the session through the controller. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------------------------ | +| command | string | Yes | Name of the custom control command.| +| args | {[key: string]: any} | Yes | Parameters in key-value pair format carried in the custom control command.| +| callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | + +**Example** + +```js +let commandName = "my_command"; +let args = { + command : "This is my command" +} +controller.sendCommonCommand(commandName, args, (err) => { + if(err) { + console.info(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`); + } +}) +``` + ### on('metadataChange') on(type: 'metadataChange', filter: Array\ | 'all', callback: (data: AVMetadata) => void) @@ -2609,6 +3620,8 @@ Subscribes to the metadata change event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2618,6 +3631,7 @@ Subscribes to the metadata change event. | callback | (data: [AVMetadata](#avmetadata)) => void | Yes | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2646,6 +3660,8 @@ Subscribes to the playback state change event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2655,6 +3671,7 @@ Subscribes to the playback state change event. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | Yes | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2675,6 +3692,108 @@ controller.on('playbackStateChange', playbackFilter, (playbackState) => { }); ``` +### on('sessionEvent')10+ + +on(type: 'sessionEvent', callback: (sessionEvent: string, args: {[key:string]: Object}) => void): void + +Subscribes to session event changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The event **'sessionEvent'** is reported when the session event changes.| +| callback | (sessionEvent: string, args: {[key:string]: object}) => void | Yes | Callback used for subscription. **sessionEvent** in the callback indicates the name of the session event that changes, and **args** indicates the parameters carried in the event. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**Example** + +```js +controller.on('sessionEvent', (sessionEvent, args) => { + console.info(`OnSessionEvent, sessionEvent is ${sessionEvent}, args: ${JSON.stringify(args)}`); +}); +``` + +### on('queueItemsChange')10+ + +on(type: 'queueItemsChange', callback: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void + +Subscribes to playlist item changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------------- | +| type | string | Yes | Event type. The event **'queueItemsChange'** is reported when one or more items in the playlist changes.| +| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | Yes | Callback used for subscription. The **items** parameter in the callback indicates the changed items in the playlist. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**Example** + +```js +controller.on('queueItemsChange', (items) => { + console.info(`OnQueueItemsChange, items length is ${items.length}`); +}); +``` + +### on('queueTitleChange')10+ + +on(type: 'queueTitleChange', callback: (title: string) => void): void + +Subscribes to playlist name changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The event **'queueTitleChange'** is reported when the playlist name changes.| +| callback | (title: string) => void | Yes | Callback used for subscription. The **title** parameter in the callback indicates the changed playlist name. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**Example** + +```js +controller.on('queueTitleChange', (title) => { + console.info(`queueTitleChange, title is ${title}`); +}); +``` + ### on('sessionDestroy') on(type: 'sessionDestroy', callback: () => void) @@ -2683,6 +3802,8 @@ Subscribes to the session destruction event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2691,6 +3812,7 @@ Subscribes to the session destruction event. | callback | () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2714,6 +3836,8 @@ Subscribes to the session activation state change event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2722,6 +3846,7 @@ Subscribes to the session activation state change event. | callback | (isActive: boolean) => void | Yes | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2745,6 +3870,8 @@ Subscribes to valid command changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2753,6 +3880,7 @@ Subscribes to valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | Yes | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2777,6 +3905,8 @@ Subscribes to output device changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -2785,6 +3915,7 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2808,14 +3939,17 @@ Unsubscribes from metadata changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------ | | type | string | Yes | Event type. The event **'metadataChange'** is reported when the session metadata changes. | -| callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2836,14 +3970,17 @@ Unsubscribes from playback state changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | type | string | Yes | Event type. The event **'playbackStateChange'** is reported when the playback state changes. | -| callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2856,6 +3993,99 @@ For details about the error codes, see [AVSession Management Error Codes](../err controller.off('playbackStateChange'); ``` +### off('sessionEvent')10+ + +off(type: 'sessionEvent', callback?: (sessionEvent: string, args: {[key:string]: Obejct}) => void): void + +Unsubscribes from session event changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'sessionEvent'**. | +| callback | (sessionEvent: string, args: {[key:string]: object}) => void | No | Callback used for unsubscription. **sessionEvent** in the callback indicates the name of the session event that changes, and **args** indicates the parameters carried in the event.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**Example** + +```js +controller.off('sessionEvent'); +``` + +### off('queueItemsChange')10+ + +off(type: 'queueItemsChange', callback?: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void + +Unsubscribes from playback item changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'queueItemsChange'**. | +| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | No | Callback used for unsubscription. The **items** parameter in the callback indicates the changed items in the playback.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**Example** + +```js +controller.off('queueItemsChange'); +``` + +### off('queueTitleChange')10+ + +off(type: 'queueTitleChange', callback?: (title: string) => void): void + +Unsubscribes from playlist name changes. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'queueTitleChange'**. | +| callback | (title: string) => void | No | Callback used for unsubscription. The **items** parameter in the callback indicates the changed playlist name.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**Example** + +```js +controller.off('queueTitleChange'); +``` + ### off('sessionDestroy') off(type: 'sessionDestroy', callback?: () => void) @@ -2864,14 +4094,17 @@ Unsubscribes from the session destruction event. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ----------------------------------------------------- | | type | string | Yes | Event type. The event **'sessionDestroy'** is reported when the session is destroyed. | -| callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2892,14 +4125,17 @@ Unsubscribes from session activation state changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ----------------------------------------------------- | | type | string | Yes | Event type. The event **'activeStateChange'** is reported when the session activation state changes. | -| callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2920,14 +4156,17 @@ Unsubscribes from valid command changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | | type | string | Yes | Event type. The event **'validCommandChange'** is reported when the supported commands change. | -| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the command is a set of valid commands.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the callback is a set of valid commands.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message | @@ -2948,14 +4187,17 @@ Unsubscribes from output device changes. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ | | type | string | Yes | Event type. The event **'outputDeviceChange'** is reported when the output device changes. | -| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | +| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** + For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID | Error Message | @@ -2989,6 +4231,8 @@ Enumerates the session types supported by the session. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Description| | ----- | ------ | ---- | | audio | string | Audio session.| @@ -3018,6 +4262,8 @@ Enumerates the commands that can be sent to a session. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Description | | -------------- | ------ | ------------ | | play | string | Play the media. | @@ -3038,6 +4284,8 @@ Describes the command that can be sent to the session. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------- | ---- | -------------- | | command | [AVControlCommandType](#avcontrolcommandtype) | Yes | Command. | @@ -3049,6 +4297,8 @@ Describes the media metadata. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | --------------- |-------------------------| ---- |---------------------------------------------------------------------| | assetId | string | Yes | Media ID. | @@ -3067,12 +4317,42 @@ Describes the media metadata. | previousAssetId | string | No | ID of the previous media asset. | | nextAssetId | string | No | ID of the next media asset. | +## AVMediaDescription10+ + +Describes the attributes related to the media metadata of the playlist. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +| Name | Type | Mandatory | Description | +| ------------ | ----------------------- | ---- | ----------------------- | +| mediaId | string | Yes | Media ID of the playlist. | +| title | string | No | Name of the playlist. | +| subtitle | string | No | Subname of the playlist. | +| description | string | No | Description of the playlist. | +| icon | image.PixelMap | No | Pixel map of the image of the playlist.| +| iconUri | string | No | Path of the image of the playlist.| +| extras | {[key: string]: any} | No | Additional fields of the playlist. | +| mediaUri | string | No | Media URI. | + +## AVQueueItem10+ + +Describes the attributes of an item in the playlist. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------ | ---- | --------------------------- | +| itemId | number | Yes | ID of an item in the playlist. | +| description | [AVMediaDescription](#avmediadescription10) | Yes | Media metadata of the item in the playlist. | + ## AVPlaybackState Describes the information related to the media playback state. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | ------------ | ------------------------------------- | ---- | ------- | | state | [PlaybackState](#playbackstate) | No | Playback state.| @@ -3088,6 +4368,8 @@ Describes the information related to the playback position. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------ | | elapsedTime | number | Yes | Elapsed time, in ms.| @@ -3099,6 +4381,8 @@ Describes the information related to the output device. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | ---------- | -------------- | ---- | ---------------------- | | isRemote | boolean | Yes | Whether the device is connected. | @@ -3111,6 +4395,8 @@ Enumerates the media playback states. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Value | Description | | --------------------------- | ---- | ----------- | | PLAYBACK_STATE_INITIAL | 0 | Initial. | @@ -3128,6 +4414,8 @@ Enumerates the loop modes of media playback. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Value | Description | | ------------------ | ---- | -------- | | LOOP_MODE_SEQUENCE | 0 | Sequential playback.| @@ -3141,6 +4429,8 @@ Enumerates the error codes used in the media session. **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Value | Description | | ------------------------------ | ------- | ------------------------------- | | ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception. | diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 775bc6665152c9d2870e28f677022d8734a551fe..325b32ef4780b5a884cdb2f07b0eaf73c124fcc4 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -161,7 +161,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -253,7 +253,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -339,7 +339,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 6231cab50066c32fcbed5bfaf11def7838b0329e..4e4a654f4f314d0447c3cf5bd32c6f7f550affc8 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -30,10 +30,10 @@ Describes battery information. | batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | | isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | | batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | -| estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. **System API**: This is a system API. | -| totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. **System API**: This is a system API. | -| nowCurrent9+ | number | Yes | No | Battery current of the device, in unit of mA. **System API**: This is a system API. | -| remainingEnergy9+ | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. **System API**: This is a system API.| +| estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. This is a system API. | +| totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | +| nowCurrent9+ | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. | +| remainingEnergy9+ | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.| ## BatteryPluggedType diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 7523cde56562a53a6129d810dff30ba95a718a64..ff1c5faec320b9c7deb874eee5f8329df524a735 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -160,9 +160,9 @@ bundle.getBundleInstaller().then(installer => { Describes the parameters required for bundle installation, recovery, or uninstall. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework - **System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | ----------- | ------- | ---- | ---- | ------------------ | @@ -174,17 +174,17 @@ Describes the parameters required for bundle installation, recovery, or uninstal Describes the bundle installation or uninstall status. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework - **System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | -| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode). | +| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode)| | statusMessage | string | Yes | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstallation failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstallation permission. | ## Obtaining the Sandbox Path -For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the attribute in [Context](js-apis-inner-application-uiAbilityContext.md#abilitycontext). The following describes how to obtain the sandbox path. **Example** ``` ts diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md index 2537274b8d5bd50d6c47258be2770bd5d51a9733..8997e94099071ce9b4e806f06b008477352af187 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @@ -9,16 +9,15 @@ The **ApplicationInfo** module defines the application information. A system app ## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Core - | Name | Type | Readable| Writable| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | +| description | string | Yes | No | Description of the application, for example, "description": $string: mainability_description". | | descriptionId | number | Yes | No | ID of the application description. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | +| label | string | Yes | No | Application name, for example, "label": "$string: mainability_description".| | labelId | number | Yes | No | ID of the application label. | -| icon | string | Yes | No | Application icon. | +| icon | string | Yes | No | Application icon, for example, "icon": "$media:icon". | | iconId | number | Yes | No | ID of the application icon. | | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | permissions | Array\ | Yes | No | Permissions required for accessing the application. The permissions can be obtained by passing in **GET_APPLICATION_INFO_WITH_PERMISSION** to the **appFlags** parameter of [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo).| @@ -27,9 +26,9 @@ The **ApplicationInfo** module defines the application information. A system app | removable | boolean | Yes | No | Whether the application is removable. | | accessTokenId | number | Yes | No | Access token ID of the application. | | uid | number | Yes | No | UID of the application. | -| iconResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Icon resource of the application. | -| labelResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Label resource of the application. | -| descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application. | +| iconResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application icon. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details. | +| labelResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application label. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details. | +| descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application description. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details.| | appDistributionType | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. | | appProvisionType | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**. | | systemApp | boolean | Yes | No | Whether the application is a system application. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5e16b3342c0f6a196c3da5362f950eecacf4c4a5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md @@ -0,0 +1,19 @@ +# OverlayModuleInfo + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +The **OverlayModuleInfo** module provides information about a module with the overlay feature. A system application can obtain such information of the specified application through [overlay.getOverlayModuleInfoByBundleName](js-apis-overlay.md#overlaygetoverlaymoduleinfobybundlename), and a third-party application can obtain such information of the current application through [overlay.getOverlayModuleInfo](js-apis-overlay.md#overlaygetoverlaymoduleinfo). + +## OverlayModuleInfo + + **System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +| Name | Type | Readable| Writable| Description | +| --------------------- | ---------------------------------------------------| ---- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | No | Bundle name of the application to which the module with the overlay feature belongs. | +| moduleName | string | Yes | No | HAP name of the module with the overlay feature. | +| targetModuleName | string | Yes | No | HAP name of the target module specified by the module with the overlay feature. | +| priority | number | Yes | No | Priority of the module with the overlay feature. | +| state | number | Yes | No | Whether the module with the overlay feature is disabled. The value **0** means that the module is disabled, and **1** means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index a346a61081df95cc18e35898c07674db7bd3f318..1503f821c413923f28e11a31a77c5cd2eb07c101 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -2215,7 +2215,7 @@ try { ### bundleManager.getProfileByAbility -getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback>): void; +getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void; Obtains the JSON strings of the configuration file based on the given module ame, ability name, and metadata name. This API uses an asynchronous callback to return the result. @@ -2266,7 +2266,7 @@ try { ### bundleManager.getProfileByAbility -getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise>; +getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise\\>; Obtains the JSON strings of the configuration file based on the given module ame, ability name, and metadata name. This API uses a promise to return the result. @@ -2336,7 +2336,7 @@ try { ### bundleManager.getProfileByExtensionAbility -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback>): void; +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void; Obtains the JSON strings of the configuration file based on the given module ame, Extension ability name, and metadata name. This API uses an asynchronous callback to return the result. @@ -2386,7 +2386,7 @@ try { ### bundleManager.getProfileByExtensionAbility -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise>; +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise\\>; Obtains the JSON strings of the configuration file based on the given module ame, Extension ability name, and metadata name. This API uses a promise to return the result. @@ -2659,7 +2659,6 @@ try { ### bundleManager.getApplicationInfoSync getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); -getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); Synchronously obtains the application information based on the given bundle name, application flags, and user ID. @@ -2710,6 +2709,42 @@ try { } ``` +### bundleManager.getApplicationInfoSync + +getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); + +Synchronously obtains the application information based on the given bundle name and application flags. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------- | ---- | ----------------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------- | +| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Application information obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700026 | The specified bundle is disabled. | + +**Example** + ```ts import bundleManager from '@ohos.bundle.bundleManager'; import hilog from '@ohos.hilog'; @@ -2727,7 +2762,6 @@ try { ### bundleManager.getBundleInfoSync getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag), userId: number): [BundleInfo](js-apis-bundleManager-bundleInfo.md); -getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); Synchronously obtains the bundle information based on the given bundle name, bundle flags, and user ID. @@ -2743,7 +2777,7 @@ Synchronously obtains the bundle information based on the given bundle name, bun | ----------- | ------ | ---- | -------------------------------------------------------- | | bundleName | string | Yes | Bundle name. | | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| -| userId | number | No | User ID. | +| userId | number | Yes | User ID. | **Return value** @@ -2778,6 +2812,42 @@ try { } ``` +### bundleManager.getBundleInfoSync + +getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); + +Synchronously obtains the bundle information based on the given bundle name and bundle flags. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------- | ---- | ------------------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700026 | The specified bundle is disabled. | + +**Example** + ```ts import bundleManager from '@ohos.bundle.bundleManager'; import hilog from '@ohos.hilog'; @@ -2790,3 +2860,37 @@ try { hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` + +## ModuleType + +Enumerates the module types. + + **System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Name | Value | Description | +| ------- | ---- | -------------------- | +| ENTRY | 1 | Main module of the application. | +| FEATURE | 2 | Dynamic feature module of the application.| +| SHARED | 3 | Dynamic shared library module of the application. | + +## BundleType + +Enumerates the bundle types. + + **System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Name | Value | Description | +| -------------- | ---- | --------------- | +| APP | 0 | The bundle is a common application. | +| ATOMIC_SERVICE | 1 | The bundle is an atomic service.| + +## AtomicServiceModuleType + +Enumerates the module types of an atomic service. + + **System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Name | Value | Description | +| ------ | ---- | --------------------------- | +| NORMAL | 0 | Page package in the atomic service. | +| MAIN | 1 | Landing page package in the atomic service.| diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index 11f54832d6556e24f35cd1baedee0d9abfe39079..bf20a7708d16aa7a8f8daeb7f43c8f5fb60580c3 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -16,7 +16,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; | Permission | Permission Level | Description | | ------------------------------------ | ----------- | ------------------------------ | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | Permission to listen for bundle installation, uninstall, and updates.| +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | Permission to listen for bundle installation, uninstall, and updates.| For details, see [Permission Levels](../../security/accesstoken-overview.md). @@ -33,7 +33,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md). ## bundleMonitor.on -on(type: BundleChangedEvent, callback: callback\): void; +on(type: BundleChangedEvent, callback: Callback\): void; Subscribes to bundle installation, uninstall, and update events. @@ -66,7 +66,7 @@ try { ## bundleMonitor.off -off(type: BundleChangedEvent, callback?: callback\): void; +off(type: BundleChangedEvent, callback?: Callback\): void; Unsubscribes from bundle installation, uninstall, and update events. diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d..6b6222abe96a415e28290892f8e6a215c1e98478 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -4,32 +4,32 @@ The **call** module provides call management functions, including making calls, To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange). ->**NOTE**
+>**NOTE** +> >The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```js import call from '@ohos.telephony.call'; ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, callback: AsyncCallback\): void Initiates a call. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.PLACE\_CALL (a system permission) +**Required Permissions**: ohos.permission.PLACE_CALL **System capability**: SystemCapability.Telephony.CallManager **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------- | ---- | -------------------------------- | -| phoneNumber | string | Yes | Phone number. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------- | ---- | --------------------------------------- | +| phoneNumber | string | Yes | Phone number. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure| **Example** @@ -40,23 +40,23 @@ call.dial("138xxxxxxxx", (err, data) => { ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\): void -Initiates a call based on the specified options. This API uses an asynchronous callback to return the result. +Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.PLACE\_CALL (a system permission) +**Required Permissions**: ohos.permission.PLACE_CALL **System capability**: SystemCapability.Telephony.CallManager **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ---------------------------- | ---- | --------------------------------------- | -| phoneNumber | string | Yes | Phone number. | -| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure | +| phoneNumber | string | Yes | Phone number. | +| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure| **Example** @@ -69,28 +69,28 @@ call.dial("138xxxxxxxx", { ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, options?: DialOptions\): Promise -Initiates a call based on the specified options. This API uses a promise to return the result. +Initiates a call. You can set call options as needed. This API uses a promise to return the result. -**Required permission**: ohos.permission.PLACE\_CALL (a system permission) +**Required Permissions**: ohos.permission.PLACE_CALL **System capability**: SystemCapability.Telephony.CallManager **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | -------------------------------------- | -| phoneNumber | string | Yes | Phone number. | -| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. | +| phoneNumber | string | Yes | Phone number. | +| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call.| **Return value** -| Type | Description | -| ---------------------- | ---------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result.
- **true**: success
- **false**: failure | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result.
- **true**: success
- **false**: failure| **Example** @@ -105,6 +105,142 @@ promise.then(data => { }); ``` + +## call.dialCall9+ + +dialCall\(phoneNumber: string, callback: AsyncCallback\): void + +Initiates a call. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required Permissions**: ohos.permission.PLACE_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------- | ---- | --------------------------------------- | +| phoneNumber | string | Yes | Phone number. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +call.dialCall("138xxxxxxxx", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.dialCall9+ + +dialCall\(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback\): void + +Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required Permissions**: ohos.permission.PLACE_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------------- | ---- | ------------------------------------ | +| phoneNumber | string | Yes | Phone number. | +| options | [DialCallOptions](#dialcalloptions9)| Yes | Call options, which carry other configuration information of the call. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +call.dialCall("138xxxxxxxx", { + accountId: 0, + videoState: 0, + dialScene: 0, + dialType: 0, +}, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.dialCall9+ + +dialCall\(phoneNumber: string, options?: DialCallOptions\): Promise + +Initiates a call. You can set call options as needed. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required Permissions**: ohos.permission.PLACE_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------------- | ---- | -------------------------------------- | +| phoneNumber | string | Yes | Phone number. | +| options | [DialCallOptions](#dialcalloptions9)| No | Call option, which indicates whether the call is a voice call or video call.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. | + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +try { + call.dialCall('138xxxxxxxx'); + console.log(`dialCall success, promise: data->${JSON.stringify(data)}`); +} catch (error) { + console.log(`dialCall fail, promise: err->${JSON.stringify(error)}`); +} +``` + + ## call.makeCall7+ makeCall(phoneNumber: string, callback: AsyncCallback\): void @@ -115,16 +251,27 @@ Launches the call screen and displays the dialed number. This API uses an asynch **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------------------------- | ---- | ------------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** ```js -call.makeCall("138xxxxxxxx", err => { - console.log(`makeCall callback: err->${JSON.stringify(err)}`); +call.makeCall("138xxxxxxxx", err => { + console.log(`makeCall callback: err->${JSON.stringify(err)}`); }); ``` @@ -139,24 +286,35 @@ Launches the call screen and displays the dialed number. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | -| phoneNumber | string | Yes | Phone number. | +| phoneNumber | string | Yes | Phone number.| **Return value** | Type | Description | | ------------------- | --------------------------------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** ```js -let promise = call.makeCall("138xxxxxxxx"); -promise.then(() => { - console.log(`makeCall success`); -}).catch(err => { - console.error(`makeCall fail, promise: err->${JSON.stringify(err)}`); +let promise = call.makeCall("138xxxxxxxx"); +promise.then(() => { + console.log(`makeCall success`); +}).catch(err => { + console.error(`makeCall fail, promise: err->${JSON.stringify(err)}`); }); ``` @@ -170,9 +328,9 @@ Checks whether a call is in progress. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Callback used to return the result.
- **true**: A call is in progress.
- **false**: No call is in progress. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Callback used to return the result.
- **true**: A call is in progress.
- **false**: No call is in progress.| **Example** @@ -195,7 +353,7 @@ Checks whether a call is in progress. This API uses a promise to return the resu | Type | Description | | ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to return the result. | +| Promise<boolean> | Promise used to return the result.| **Example** @@ -219,9 +377,9 @@ Obtains the call status. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback<[CallState](#callstate)> | Yes | Callback used to return the result. | +| callback | AsyncCallback<[CallState](#callstate)> | Yes | Callback used to return the result.| **Example** @@ -244,7 +402,7 @@ Obtains the call status. This API uses a promise to return the result. | Type | Description | | -------------------------------------- | --------------------------------------- | -| Promise<[CallState](#callstate)> | Promise used to return the result. | +| Promise<[CallState](#callstate)> | Promise used to return the result.| **Example** @@ -269,7 +427,7 @@ Checks whether a device supports voice calls. | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | - **true**: The device supports voice calls.
- **false**: The device does not support voice calls. | +| boolean | - **true**: The device supports voice calls.
- **false**: The device does not support voice calls.| ```js let result = call.hasVoiceCapability(); @@ -286,10 +444,21 @@ Checks whether the called number is an emergency number. This API uses an asynch **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ---------------------------- | ---- | ------------------------------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. - **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -304,17 +473,28 @@ call.isEmergencyPhoneNumber("138xxxxxxxx", (err, data) => { isEmergencyPhoneNumber\(phoneNumber: string, options: EmergencyNumberOptions, callback: AsyncCallback\): void -Checks whether the called number is an emergency number based on the specified phone number options. This API uses an asynchronous callback to return the result. +Checks whether the called number is an emergency number based on the phone number. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CallManager **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | -| phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number options. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| phoneNumber | string | Yes | Phone number. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. - **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -329,22 +509,33 @@ call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, data) => { isEmergencyPhoneNumber\(phoneNumber: string, options?: EmergencyNumberOptions\): Promise -Checks whether the called number is an emergency number based on the specified phone number options. This API uses a promise to return the result. +Checks whether the called number is an emergency number based on the phone number. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CallManager **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------------- | ---- | -------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number.| **Return value** | Type | Description | | ---------------------- | --------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. | +| Promise<boolean> | Promise used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -369,10 +560,21 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -386,7 +588,7 @@ call.formatPhoneNumber("138xxxxxxxx", (err, data) => { formatPhoneNumber\(phoneNumber: string, options: NumberFormatOptions, callback: AsyncCallback\): void -Formats a phone number based on the specified formatting options. This API uses an asynchronous callback to return the result. +Formats a phone number based on specified formatting options. This API uses an asynchronous callback to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -394,11 +596,22 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | No | Number formatting options, for example, country code. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. | +| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -415,7 +628,7 @@ call.formatPhoneNumber("138xxxxxxxx", { formatPhoneNumber\(phoneNumber: string, options?: NumberFormatOptions\): Promise -Formats a phone number based on the specified formatting options. This API uses a promise to return the result. +Formats a phone number based on specified formatting options. This API uses a promise to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -423,16 +636,27 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ---------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | No | Number formatting options, for example, country code.| **Return value** | Type | Description | | --------------------- | ------------------------------------------- | -| Promise<string> | Promise used to return the result. | +| Promise<string> | Promise used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -459,11 +683,22 @@ The phone number must match the specified country code. For example, for a China **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ----------------------------------------------------- | | phoneNumber | string | Yes | Phone number. | | countryCode | string | Yes | Country code, for example, **CN** (China). All country codes are supported. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -488,16 +723,27 @@ All country codes are supported. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| countryCode | string | Yes | Country code, for example, **CN** (China). All country codes are supported. | +| countryCode | string | Yes | Country code, for example, **CN** (China). All country codes are supported.| **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise<string> | Promise used to return the result. | +| Promise<string> | Promise used to return the result.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -514,9 +760,9 @@ promise.then(data => { muteRinger\(callback: AsyncCallback\): void -Mutes the ringtone while it is playing. This API uses an asynchronous callback to return the result. +Mutes the ringtone while it is playing. It does not work if the ringtone has been muted. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -528,6 +774,17 @@ This is a system API. | ----------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -541,9 +798,9 @@ call.muteRinger((err, data) => { muteRinger\(\): Promise -Mutes the ringtone while it is playing. This API uses a promise to return the result. +Mutes the ringtone while it is playing. It does not work if the ringtone has been muted. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -555,6 +812,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -566,13 +835,14 @@ promise.then(data => { }); ``` -## call.answer7+ -answer\(callId: number, callback: AsyncCallback\): void +## call.answerCall7+ + +answerCall\(callId: number, callback: AsyncCallback\): void -Answers a call based on the specified call ID. This API uses an asynchronous callback to return the result. +Answers a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -585,22 +855,34 @@ This is a system API. | callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -call.answer(1, (err, data) => { +call.answerCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.answer7+ +## call.answerCall7+ -answer(callId?: number\): Promise +answerCall(callId?: number\): Promise -Answers a call based on the specified call ID. This API uses a promise to return the result. +Answers a call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -618,24 +900,37 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -let promise = call.answer(1); +let promise = call.answerCall(1); promise.then(data => { - console.log(`answer success, promise: data->${JSON.stringify(data)}`); + console.log(`answerCall success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`answer fail, promise: err->${JSON.stringify(err)}`); + console.error(`answerCall fail, promise: err->${JSON.stringify(err)}`); }); ``` -## call.hangup7+ -hangup\(callId: number, callback: AsyncCallback\): void +## call.answerCall9+ -Ends a call. This API uses an asynchronous callback to return the result. +answerCall\(callback: AsyncCallback\): void + +Answers a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -645,25 +940,36 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -call.hangup(1, (err, data) => { +call.answerCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.answer9+ +## call.hangUpCall7+ -answer\(callback: AsyncCallback\): void +hangUpCall\(callId: number, callback: AsyncCallback\): void -Answers a call.This API uses an asynchronous callback to return the result. +Ends a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -673,24 +979,37 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -call.answer((err, data) => { +call.hangUpCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.hangup7+ +## call.hangUpCall7+ -hangup\(callId?: number\): Promise +hangUpCall\(callId?: number\): Promise -Ends a call based on the specified call ID. This API uses a promise to return the result. +Ends a call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -708,24 +1027,37 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -let promise = call.hangup(1); +let promise = call.hangUpCall(1); promise.then(data => { - console.log(`hangup success, promise: data->${JSON.stringify(data)}`); + console.log(`hangUpCall success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`hangup fail, promise: err->${JSON.stringify(err)}`); + console.error(`hangUpCall fail, promise: err->${JSON.stringify(err)}`); }); ``` -## call.hangup9+ -hangup\(callback: AsyncCallback\): void +## call.hangUpCall9+ + +hangUpCall\(callback: AsyncCallback\): void Ends a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -737,22 +1069,35 @@ This is a system API. | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + + **Example** ```js -call.hangup((err, data) => { +call.hangUpCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ +## call.rejectCall7+ -reject(callId: number, callback: AsyncCallback\): void +rejectCall(callId: number, callback: AsyncCallback\): void -Rejects a call based on the specified call ID. This API uses an asynchronous callback to return the result. +Rejects a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -765,22 +1110,35 @@ This is a system API. | callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -call.reject(1, (err, data) => { +call.rejectCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ -reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void +## call.rejectCall7+ + +rejectCall\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void -Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. +Rejects a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -794,25 +1152,37 @@ This is a system API. | options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js let rejectMessageOptions={ messageContent: "Unknown number blocked" } -call.reject(1, rejectMessageOptions, (err, data) => { +call.rejectCall(1, rejectMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ +## call.rejectCall7+ -reject(callId?: number, options?: RejectMessageOptions\): Promise +rejectCall(callId?: number, options?: RejectMessageOptions\): Promise -Rejects a call based on the specified call ID and options. This API uses a promise to return the result. +Rejects a call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -831,28 +1201,40 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js let rejectMessageOptions={ messageContent: "Unknown number blocked" } -let promise = call.reject(1, rejectMessageOptions); +let promise = call.rejectCall(1, rejectMessageOptions); promise.then(data => { - console.log(`reject success, promise: data->${JSON.stringify(data)}`); + console.log(`rejectCall success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`reject fail, promise: err->${JSON.stringify(err)}`); + console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`); }); ``` -## call.reject9+ +## call.rejectCall9+ -reject\(callback: AsyncCallback\): void +rejectCall\(callback: AsyncCallback\): void Rejects a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -864,22 +1246,34 @@ This is a system API. | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| -**Example:** +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** ```js -call.reject((err, data) => { +call.rejectCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject9+ +## call.rejectCall9+ -reject\(options: RejectMessageOptions, callback: AsyncCallback\): void +rejectCall\(options: RejectMessageOptions, callback: AsyncCallback\): void Rejects a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -892,13 +1286,25 @@ This is a system API. | options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example:** +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** ```js let rejectMessageOptions={ messageContent: "Unknown number blocked" } -call.reject(rejectMessageOptions, (err, data) => { +call.rejectCall(rejectMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -910,7 +1316,7 @@ holdCall\(callId: number, callback: AsyncCallback\): void Holds a call based on the specified call ID. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -923,6 +1329,18 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -938,7 +1356,7 @@ holdCall\(callId: number\): Promise Holds a call based on the specified call ID. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -956,6 +1374,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -973,7 +1403,7 @@ unHoldCall\(callId: number, callback: AsyncCallback\): void Unholds a call based on the specified call ID. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -986,6 +1416,18 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1001,7 +1443,7 @@ unHoldCall\(callId: number\): Promise Unholds a call based on the specified call ID. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -1019,6 +1461,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1036,7 +1490,7 @@ switchCall\(callId: number, callback: AsyncCallback\): void Switches a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -1049,6 +1503,18 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1064,7 +1530,7 @@ switchCall\(callId: number\): Promise Switches a call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.ANSWER_CALL @@ -1082,6 +1548,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1099,7 +1577,7 @@ combineConference\(callId: number, callback: AsyncCallback\): void Combines two calls into a conference call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1110,6 +1588,17 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1125,7 +1614,7 @@ combineConference\(callId: number\): Promise Combines two calls into a conference call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1141,6 +1630,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1158,7 +1658,7 @@ getMainCallId\(callId: number, callback: AsyncCallback\): void Obtains the main call ID. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1169,6 +1669,18 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<number> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + + **Example** ```js @@ -1184,7 +1696,7 @@ getMainCallId\(callId: number\): Promise Obtains the main call ID. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1200,6 +1712,17 @@ This is a system API. | ------------------- | ------------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1217,7 +1740,7 @@ getSubCallIdList\(callId: number, callback: AsyncCallback\>\): vo Obtains the list of subcall IDs. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1228,6 +1751,17 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback\> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1243,7 +1777,7 @@ getSubCallIdList\(callId: number\): Promise\> Obtains the list of subcall IDs. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1259,6 +1793,17 @@ This is a system API. | ----------------------------- | ----------------------------------- | | Promise<Array> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1276,7 +1821,7 @@ getCallIdListForConference\(callId: number, callback: AsyncCallback> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1302,7 +1858,7 @@ getCallIdListForConference\(callId: number\): Promise\> Obtains the list of call IDs in a conference. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1318,6 +1874,17 @@ This is a system API. | ----------------------------- | --------------------------------------- | | Promise<Array> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1335,7 +1902,7 @@ getCallWaitingStatus\(slotId: number, callback: AsyncCallback- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.

- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| + +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -1363,7 +1942,7 @@ getCallWaitingStatus\(slotId: number\): Promise Obtains the call waiting status. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1381,6 +1960,18 @@ This is a system API. | ------------------------------------------------------- | ------------------------------------------------------------ | | Promise<[CallWaitingStatus](#callwaitingstatus7)> | Promise used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1398,7 +1989,7 @@ setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback- **false**: Disable call waiting.
- **true**: Enable call waiting.| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1427,7 +2030,7 @@ setCallWaiting\(slotId: number, activate: boolean\): Promise Sets the call waiting switch. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1446,6 +2049,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1461,9 +2076,9 @@ promise.then(data => { startDTMF\(callId: number, character: string, callback: AsyncCallback\): void -Enables dual-tone multifrequency (DTMF). This API uses an asynchronous callback to return the result. +Enables DTMF. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1475,6 +2090,17 @@ This is a system API. | character | string | Yes | DTMF code. | | callback | AsyncCallback | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1490,7 +2116,7 @@ startDTMF\(callId: number, character: string\): Promise Enables DTMF. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1507,6 +2133,17 @@ This is a system API. | ------------------- | ----------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1524,7 +2161,7 @@ stopDTMF\(callId: number, callback: AsyncCallback\): void Stops DTMF. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1535,6 +2172,17 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1550,7 +2198,7 @@ stopDTMF\(callId: number\): Promise Stops DTMF. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1566,6 +2214,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1583,7 +2242,7 @@ isInEmergencyCall\(callback: AsyncCallback\): void Checks whether a call is an emergency call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1595,6 +2254,18 @@ This is a system API. | -------- | ---------------------------- | ---- | ---------- | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1610,7 +2281,7 @@ isInEmergencyCall\(\): Promise Checks whether a call is an emergency call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1622,6 +2293,18 @@ This is a system API. | ---------------------- | --------------------------- | | Promise<boolean> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1639,7 +2322,7 @@ on\(type: 'callDetailsChange', callback: Callback\): void Subscribes to **callDetailsChange** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1652,6 +2335,18 @@ This is a system API. | type | string | Yes | Call details change during a call.| | callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1666,7 +2361,7 @@ on\(type: 'callEventChange', callback: Callback\): void Subscribes to **callEventChange** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1679,6 +2374,18 @@ This is a system API. | type | string | Yes | Call event change during a call.| | callback | Callback<[CallEventOptions](#calleventoptions8)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1693,7 +2400,7 @@ on\(type: 'callDisconnectedCause', callback: Callback): vo Subscribes to **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1706,6 +2413,18 @@ This is a system API. | type | string | Yes | Cause of the call disconnection.| | callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1720,7 +2439,7 @@ on\(type: 'mmiCodeResult', callback: Callback\): void Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1733,6 +2452,18 @@ This is a system API. | type | string | Yes | Man-machine interface (MMI) code result.| | callback | Callback<[MmiCodeResults](#mmicoderesults9)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1747,7 +2478,7 @@ off\(type: 'callDetailsChange', callback?: Callback\): vo Unsubscribes from **callDetailsChange** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1757,9 +2488,21 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------------- | ---- | ---------------------------------- | -| type | string | Yes | Unsubscription from call details changes when a call ends.| +| type | string | Yes | IMS registration status changes.| | callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1774,7 +2517,7 @@ off\(type: 'callEventChange', callback?: Callback\): void Unsubscribes from **callEventChange** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1787,6 +2530,18 @@ This is a system API. | type | string | Yes | Unsubscription from call event changes when a call ends.| | callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1801,7 +2556,7 @@ off\(type: 'callDisconnectedCause', callback?: Callback\): Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1814,6 +2569,18 @@ This is a system API. | type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.| | callback | Callback**<**[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1828,7 +2595,7 @@ off\(type: 'mmiCodeResult', callback?: Callback\): void Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1841,6 +2608,18 @@ This is a system API. | type | 'mmiCodeResult' | Yes | MMI code result.| | callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1855,7 +2634,7 @@ isNewCallAllowed\(callback: AsyncCallback\): void Checks whether a new call is allowed. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1865,6 +2644,17 @@ This is a system API. | -------- | ---------------------------- | ---- | ---------- | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1880,7 +2670,7 @@ isNewCallAllowed\(\): Promise Checks whether a new call is allowed. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1890,6 +2680,17 @@ This is a system API. | ---------------------- | --------------------------- | | Promise<boolean> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1905,9 +2706,9 @@ promise.then(data => { separateConference\(callId: number, callback: AsyncCallback\): void -Separates a conference call. This API uses an asynchronous callback to return the result. +Separates calls from a conference call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1918,6 +2719,17 @@ This is a system API. | callId | number | Yes | Call ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1931,9 +2743,9 @@ call.separateConference(1, (err, data) => { separateConference\(callId: number\): Promise -Separates a conference call. This API uses a promise to return the result. +Separates calls from a conference call. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -1949,6 +2761,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1966,7 +2789,7 @@ getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: A Obtains the call restriction status. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1980,6 +2803,18 @@ This is a system API. | type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type. | | callback | AsyncCallback<[RestrictionStatus](#restrictionstatus8)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1995,7 +2830,7 @@ getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise Sets the call restriction status. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2084,6 +2943,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2106,7 +2977,7 @@ getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCall Obtains call transfer information. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -2120,10 +2991,22 @@ This is a system API. | type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | | callback | AsyncCallback<[CallTransferResult](#calltransferresult8)> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js -call.getCallTransferInfo(0, callTransferTyp, (err, data) => { +call.getCallTransferInfo(0, call.CallTransferType.TRANSFER_TYPE_BUSY, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2135,7 +3018,7 @@ getCallTransferInfo\(slotId: number, type: CallTransferType): Promise Sets call transfer information. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2224,6 +3131,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2246,7 +3165,7 @@ isRinging\(callback: AsyncCallback\): void Checks whether the ringtone is playing. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2258,6 +3177,18 @@ This is a system API. | -------- | ---------------------------- | ---- | ---------- | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2273,7 +3204,7 @@ isRinging\(\): Promise Checks whether the ringtone is playing. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2285,6 +3216,18 @@ This is a system API. | ---------------------- | --------------------------- | | Promise<boolean> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2302,7 +3245,7 @@ setMuted\(callback: AsyncCallback\): void Sets call muting. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2312,6 +3255,17 @@ This is a system API. | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2327,7 +3281,7 @@ setMuted\(\): Promise Sets call muting. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2337,6 +3291,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2354,7 +3319,7 @@ cancelMuted(callback: AsyncCallback): void Cancels call muting. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2364,6 +3329,17 @@ This is a system API. | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2379,7 +3355,7 @@ cancelMuted(): Promise Cancels call muting. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2389,6 +3365,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2400,13 +3387,13 @@ promise.then(data => { }); ``` -## call.setAudioDevice9+ +## call.setAudioDevice8+ setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void Sets the audio device for a call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2417,6 +3404,17 @@ This is a system API. | device | [AudioDevice](#audiodevice8) | Yes | Audio device.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2432,7 +3430,7 @@ setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: Asyn Sets the audio device for a call based on the specified options. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2444,6 +3442,17 @@ This is a system API. | options | [AudioDeviceOptions](#audiodeviceoptions9) | Yes | Audio device parameters.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2456,13 +3465,13 @@ call.setAudioDevice(1, audioDeviceOptions, (err, data) => { ``` -## call.setAudioDevice8+ +## call.setAudioDevice9+ setAudioDevice(device: AudioDevice, options?: AudioDeviceOptions): Promise Sets the audio device for a call based on the specified options. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2479,6 +3488,17 @@ This is a system API. | ------------------- | ------------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2499,7 +3519,7 @@ joinConference(mainCallId: number, callNumberList: Array, callback: Asy Joins a conference call. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2511,6 +3531,17 @@ This is a system API. | callNumberList | Array | Yes | List of call numbers.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2528,7 +3559,7 @@ joinConference(mainCallId: number, callNumberList: Array): Promise Updates the IMS call mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2608,6 +3661,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2625,7 +3689,7 @@ enableImsSwitch(slotId: number, callback: AsyncCallback): void Enables the IMS switch. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2638,6 +3702,18 @@ This is a system API. | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2652,7 +3728,7 @@ enableImsSwitch(slotId: number): Promise Enables the IMS switch. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2670,6 +3746,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2687,7 +3775,7 @@ disableImsSwitch(slotId: number, callback: AsyncCallback): void Disables the IMS switch. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2700,6 +3788,18 @@ This is a system API. | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2714,7 +3814,7 @@ disableImsSwitch(slotId: number): Promise Disables the IMS switch. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2732,6 +3832,18 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2749,7 +3861,7 @@ isImsSwitchEnabled(slotId: number, callback: AsyncCallback): void Checks whether the IMS switch is enabled. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2760,6 +3872,17 @@ This is a system API. | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2774,7 +3897,7 @@ isImsSwitchEnabled(slotId: number): Promise Checks whether the IMS switch is enabled. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2790,6 +3913,17 @@ This is a system API. | ------------------- | --------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2801,20 +3935,32 @@ promise.then(data => { }); ``` - ## DialOptions -Defines the dialup options. +Provides an option for determining whether a call is a video call. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | -| ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------- | ---- | ----------------------------------------------------------------------------------------------- | | extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| -| accountId 8+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
This is a system API. | -| videoState 8+ | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | -| dialScene 8+ | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | -| dialType 8+ | [DialType](#dialtype8) | No | Dialup type. This is a system API. | +| accountId 8+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
This is a system API. | +| videoState 8+ | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | +| dialScene 8+ | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | +| dialType 8+ | [DialType](#dialtype8) | No | Dialup type. This is a system API. | + +## DialCallOptions9+ + +Defines options for initiating a call. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | +| accountId 9+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
This is a system API.| +| videoState 9+ | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | +| dialScene 9+ | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | +| dialType 9+ | [DialType](#dialtype8) | No | Dialup type. This is a system API. | ## CallState @@ -2827,33 +3973,33 @@ Enumerates call states. | CALL_STATE_UNKNOWN | -1 | The call status fails to be obtained and is unknown. | | CALL_STATE_IDLE | 0 | No call is in progress. | | CALL_STATE_RINGING | 1 | The call is in the ringing or waiting state. | -| CALL_STATE_OFFHOOK | 2 | At least one call is in dialing, active, or on hold, and no new incoming call is ringing or waiting. | +| CALL_STATE_OFFHOOK | 2 | At least one call is in dialing, active, or on hold, and no new incoming call is ringing or waiting.| ## EmergencyNumberOptions7+ -Defines options for determining whether a number is an emergency number. +Provides an option for determining whether a number is an emergency number for the SIM card in the specified slot. **System capability**: SystemCapability.Telephony.CallManager -| Name| Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------------- | | slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| ## NumberFormatOptions7+ -Defines the number formatting options. +Provides an option for number formatting. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------------------------------------- | -| countryCode | string | No | Country code, for example, **CN** (China). All country codes are supported. The default value is **CN**. | +| countryCode | string | No | Country code, for example, **CN** (China). All country codes are supported. The default value is **CN**.| ## ImsCallMode8+ Enumerates IMS call modes. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2869,23 +4015,23 @@ This is a system API. Enumerates audio devices. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager | Name | Value | Description | | -------------------- | ---- | ------------ | -| DEVICE_EARPIECE | 0 | Earpiece. | -| DEVICE_SPEAKER | 1 | Speaker.| -| DEVICE_WIRED_HEADSET | 2 | Wired headset.| +| DEVICE_EARPIECE | 0 | Headset device. | +| DEVICE_SPEAKER | 1 | Speaker device.| +| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| | DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | -| DEVICE_MIC | 4 | Microphone. | +| DEVICE_MIC | 4 | Microphone device| ## CallRestrictionType8+ Enumerates call restriction types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2904,7 +4050,7 @@ This is a system API. Defines the call transfer information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2915,14 +4061,14 @@ This is a system API. | settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| | startHour9+ | number | No | Hour in the start time.| | startMinute9+ | number | No | Minute in the start time.| -| endHour9+ | number | No | Hour in the end time.| +| endHour9+ | number | No | Minute in the end time.| | endMinute9+ | number | No | Minute in the end time.| ## CallTransferType8+ Enumerates call transfer types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2937,7 +4083,7 @@ This is a system API. Enumerates call transfer setting types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2952,11 +4098,11 @@ This is a system API. Defines the call attribute options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | --------------- | ---------------------------------------- | ---- | -------------- | | accountNumber | string | Yes | Account number. | | speakerphoneOn | boolean | Yes | Speakerphone on.| @@ -2973,7 +4119,7 @@ This is a system API. Enumerates conference states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -2988,7 +4134,7 @@ This is a system API. Enumerates call types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3001,9 +4147,9 @@ This is a system API. ## VideoStateType7+ -Enumerates video state types. +Video state type. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3016,7 +4162,7 @@ This is a system API. Enumerates detailed call states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3036,11 +4182,11 @@ This is a system API. Defines the call restriction information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------ | | type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type.| | password | string | Yes | Password. | @@ -3050,7 +4196,7 @@ This is a system API. Enumerates call restriction modes. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3063,11 +4209,11 @@ This is a system API. Defines the call event options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------------ | ---- | -------------- | | eventId | [CallAbilityEventId](#callabilityeventid8) | Yes | Call ability event ID.| @@ -3075,7 +4221,7 @@ This is a system API. Enumerates call ability event IDs. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3088,7 +4234,7 @@ This is a system API. Enumerates dialup scenarios. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3102,7 +4248,7 @@ This is a system API. Enumerates dialup types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3116,11 +4262,11 @@ This is a system API. Defines options for the call rejection message. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------------- | ------ | ---- | -------- | | messageContent | string | Yes | Message content.| @@ -3128,7 +4274,7 @@ This is a system API. Defines the call transfer result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3138,14 +4284,14 @@ This is a system API. | number | string | Yes | Call transfer number. | | startHour9+ | number | Yes | Hour in the start time.| | startMinute9+ | number | Yes | Minute in the start time.| -| endHour9+ | number | Yes | Hour in the end time.| +| endHour9+ | number | Yes | Minute in the end time.| | endMinute9+ | number | Yes | Minute in the end time.| ## CallWaitingStatus7+ Enumerates call waiting states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3158,7 +4304,7 @@ This is a system API. Enumerates call restriction states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3171,7 +4317,7 @@ This is a system API. Enumerates call transfer states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3184,7 +4330,7 @@ This is a system API. Defines the cause of a call disconnection. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3197,7 +4343,7 @@ This is a system API. Enumerates causes of call disconnection. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3287,7 +4433,7 @@ This is a system API. Defines the MMI code result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3298,9 +4444,9 @@ This is a system API. ## MmiCodeResult9+ -Enumerates MMI code results. +Defines the MMI code result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager @@ -3313,7 +4459,7 @@ This is a system API. Defines audio device options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CallManager diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index b30722bd2fddd6ef83914ffe6b8a3421831935ce..4238ee5df2b8a9bf894b83d23b9fcb11ddb9325d 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -2,7 +2,8 @@ > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -30,6 +31,15 @@ Obtains a **CameraManager** instance. This API returns the result synchronously. | ----------------------------------------------- | ---------------------------- | | [CameraManager](#cameramanager) | **CameraManager** instance obtained. | +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -254,6 +264,14 @@ Creates a **CameraInput** instance with the specified **CameraDevice** object. T | ---------- | ----------------------------- | | [CameraInput](#camerainput) | **CameraInput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -290,6 +308,14 @@ Creates a **CameraInput** instance with the specified camera position and type. | ---------- | ----------------------------- | | [CameraInput](#camerainput) | **CameraInput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -326,6 +352,14 @@ Creates a **PreviewOutput** instance. This API returns the result synchronously. | ---------- | ----------------------------- | | [PreviewOutput](#previewoutput) | **PreviewOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -360,6 +394,14 @@ Creates a **PhotoOutput** instance. This API returns the result synchronously. | ---------- | ----------------------------- | | [PhotoOutput](#photooutput) | **PhotoOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -394,6 +436,14 @@ Creates a **VideoOutput** instance. This API returns the result synchronously. | ---------- | ----------------------------- | | [VideoOutput](#videooutput) | **VideoOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -427,6 +477,14 @@ Creates a **MetadataOutput** instance. This API returns the result synchronously | ---------- | ----------------------------- | | [MetadataOutput](#metadataoutput) | **MetadataOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **Example** ```js @@ -454,6 +512,14 @@ Creates a **CaptureSession** instance. This API returns the result synchronously | ---------- | ----------------------------- | | [CaptureSession](#capturesession) | **CaptureSession** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -476,10 +542,10 @@ Listens for camera status changes. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | --------- | -| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The callback function returns the camera information, including the device and device status (available or unavailable). The event can be listened for only when a **CameraManager** instance is obtained.| -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | +| Name | Type | Mandatory| Description | +| -------- | -----------------| ---- | --------- | +| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the corresponding information is returned only when the device is enabled or disabled.| +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change.| | **Example** @@ -504,8 +570,8 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | --------- | -| type | string | Yes | Event type. The value is fixed at **'cameraMute'**. The callback function returns the mute status changes. The event can be listened for only when a **CameraManager** instance is obtained.| -| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. | +| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the status is returned when the camera is enabled or disabled.| +| callback | AsyncCallback\ | Yes | Callback used to return the mute status. The value **true** means that the camera is enabled, and **false** means that the camera is disabled. | **Example** @@ -629,6 +695,16 @@ Opens this camera. This API uses an asynchronous callback to return the result. | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400107 | Can not use camera cause of conflict. | +| 7400108 | Camera disabled cause of security reason. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -655,6 +731,16 @@ Opens this camera. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400107 | Can not use camera cause of conflict. | +| 7400108 | Camera disabled cause of security reason. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -679,6 +765,14 @@ Closes this camera. This API uses an asynchronous callback to return the result. | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -705,6 +799,14 @@ Closes this camera. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -727,7 +829,7 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul | Name | Type | Mandatory| Description | | -------- | -------------------------------- | --- | ------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code, for example, an error code indicating that the device is unavailable or a conflict occurs. The event can be listened for only when a **CameraInput** instance is obtained.| +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **CameraInput** instance is created. This event is triggered and the result is returned when an error occurs on the camera. For example, if the device is unavailable or a conflict occurs, the error information is returned.| | cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| | callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | @@ -761,9 +863,9 @@ Enumerates the exposure modes. | Name | Value | Description | | ----------------------------- | ---- | ----------- | -| EXPOSURE_MODE_LOCKED | 0 | Exposure locked.| -| EXPOSURE_MODE_AUTO | 1 | Auto exposure.| -| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.| +| EXPOSURE_MODE_LOCKED | 0 | Exposure locked. The metering point cannot be set.| +| EXPOSURE_MODE_AUTO | 1 | Auto exposure. The metering point can be set by calling [setMeteringPoint](#setmeteringpoint).| +| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure. The metering point cannot be set.| ## FocusMode @@ -773,10 +875,10 @@ Enumerates the focus modes. | Name | Value | Description | | -------------------------- | ---- | ------------ | -| FOCUS_MODE_MANUAL | 0 | Manual focus. | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| -| FOCUS_MODE_AUTO | 2 | Auto focus. | -| FOCUS_MODE_LOCKED | 3 | Focus locked. | +| FOCUS_MODE_MANUAL | 0 | Manual focus. The focal length of the camera can be manually set to change the focus position. However, the focal point cannot be set. | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus. The focal point cannot be set.| +| FOCUS_MODE_AUTO | 2 | Auto focus. The focal point can be set by calling [setFocusPoint](#setfocuspoint), and auto focus is performed once based on the focal point. After the auto focus operation is complete (regardless of whether the focus is successful or fails), the focus mode is locked. To enable the camera to initiate another auto focus, the application must call **CONTINUOUS_AUTO** again. | +| FOCUS_MODE_LOCKED | 3 | Focus locked. The focal point cannot be set. | ## FocusState @@ -822,6 +924,14 @@ Starts configuration for the session. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400105 | Session config locked. | + **Example** ```js @@ -847,6 +957,15 @@ Commits the configuration for this **CaptureSession** instance. This API uses an | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400102 | Operation not allow. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -873,6 +992,15 @@ Commits the configuration for this **CaptureSession** instance. This API uses a | -------------- | ------------------------ | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400102 | Operation not allow. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -904,6 +1032,15 @@ Adds a [CameraInput](#camerainput) instance to the session. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **Example** ```js @@ -935,6 +1072,15 @@ Removes a [CameraInput](#camerainput) instance from the session. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **Example** ```js @@ -966,6 +1112,15 @@ Adds a [CameraOutput](#cameraoutput) instance to the session. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **Example** ```js @@ -997,6 +1152,15 @@ Removes a [CameraOutput](#cameraoutput) instance from the session. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **Example** ```js @@ -1022,6 +1186,15 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1048,6 +1221,15 @@ Starts this **CaptureSession**. This API uses a promise to return the result. | -------------- | ------------------------ | | Promise| Promise used to return the result.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1072,6 +1254,14 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1098,6 +1288,14 @@ Stops this **CaptureSession**. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1122,6 +1320,14 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1148,6 +1354,14 @@ Releases this **CaptureSession**. This API uses a promise to return the result. | -------------- | ------------------------ | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -1172,6 +1386,14 @@ Checks whether the device has flash. This API uses an asynchronous callback to r | ---------- | ----------------------------- | | boolean | Returns **true** if the device has flash; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1203,6 +1425,14 @@ Checks whether a flash mode is supported. | ---------- | ----------------------------- | | boolean | Returns **true** if the flash mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1239,6 +1469,14 @@ Before the setting, do the following checks: | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1264,6 +1502,14 @@ Obtains the flash mode in use. | ---------- | ----------------------------- | | [FlashMode](#flashmode) | Flash mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1295,6 +1541,14 @@ Checks whether an exposure mode is supported. | ---------- | ----------------------------- | | boolean | Returns **true** if the exposure mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1320,6 +1574,14 @@ Obtains the exposure mode in use. | ---------- | ----------------------------- | | [ExposureMode](#exposuremode) | Exposure mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1351,6 +1613,14 @@ Sets an exposure mode for the device. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1376,6 +1646,14 @@ Obtains the metering point of the device. | ---------- | ----------------------------- | | [Point](#point) | Metering point obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1391,7 +1669,9 @@ try { setMeteringPoint(point: Point): void -Sets the metering point for the device. +Sets the metering point, which is the center point of the metering rectangle. The metering point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}. + +The coordinate system is based on the horizontal device direction with the device's charging port on the right. If the layout of the preview screen of an application is based on the vertical direction with the charging port on the lower side, the layout width and height are {w, h}, and the touch point is {x, y}, then the coordinate point after conversion is {y/h, 1-x/w}. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1407,6 +1687,14 @@ Sets the metering point for the device. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1433,6 +1721,14 @@ Obtains the exposure compensation values of the device. | ---------- | ----------------------------- | | Array | An array of compensation values. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1448,7 +1744,7 @@ try { setExposureBias(exposureBias: number): void -Sets an exposure compensation value for the device. +Sets an exposure compensation value (EV). Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. @@ -1460,6 +1756,14 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure | -------- | -------------------------------| ---- | ------------------- | | exposureBias | number | Yes | Exposure bias to set, which must be within the range obtained by running **getExposureBiasRange** interface. If the API call fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1486,6 +1790,14 @@ Obtains the exposure value in use. | ---------- | ----------------------------- | | number | Exposure value obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1517,6 +1829,14 @@ Checks whether a focus mode is supported. | ---------- | ----------------------------- | | boolean | Returns **true** if the focus mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1550,6 +1870,14 @@ Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to che | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1575,6 +1903,14 @@ Obtains the focus mode in use. | ---------- | ----------------------------- | | [FocusMode](#focusmode) | Focus mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1590,7 +1926,9 @@ try { setFocusPoint(point: Point): void -Sets a focal point for the device. +Sets the focal point. The focal point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}. + +The coordinate system is based on the horizontal device direction with the device's charging port on the right. If the layout of the preview screen of an application is based on the vertical direction with the charging port on the lower side, the layout width and height are {w, h}, and the touch point is {x, y}, then the coordinate point after conversion is {y/h, 1-x/w}. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1606,6 +1944,14 @@ Sets a focal point for the device. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1632,6 +1978,14 @@ Obtains the focal point of the device. | ---------- | ----------------------------- | | [Point](#point) | Focal point obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1657,6 +2011,14 @@ Obtains the focal length of the device. | ---------- | ----------------------------- | | number | Focal length obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1682,6 +2044,14 @@ Obtains the supported zoom ratio range. | ---------- | ----------------------------- | | Array | Callback used to return an array containing the minimum and maximum zoom ratios. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1697,7 +2067,7 @@ try { setZoomRatio(zoomRatio: number): void -Sets a zoom ratio for the device. +Sets a zoom ratio, with a maximum precision of two decimal places. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1713,6 +2083,14 @@ Sets a zoom ratio for the device. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1739,6 +2117,14 @@ Obtains the zoom ratio in use. | ---------- | ----------------------------- | | number | Zoom ratio obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1770,6 +2156,14 @@ Checks whether the specified video stabilization mode is supported. | ---------- | ----------------------------- | | boolean | Returns **true** if the video stabilization mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1795,6 +2189,14 @@ Obtains the video stabilization mode in use. | ---------- | ----------------------------- | | VideoStabilizationMode | Video stabilization mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1826,6 +2228,14 @@ Sets a video stabilization mode for the device. | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1849,7 +2259,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------ | -| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The callback function returns the focus state change. The event can be listened for only when the session is created.| +| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The event can be listened for when a session is created. This event is triggered only when the camera focus state changes in auto focus mode.| | callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | **Example** @@ -1872,7 +2282,7 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **CaptureSession** API, for example, **beginConfig()**, **commitConfig()**, or **addInput()**.| +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a session is created. This event is triggered and the error message is returned when an error occurs during the calling of a session-related API such as **beginConfig()**, **commitConfig()**, and **addInput**.| | callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | **Example** @@ -1905,6 +2315,14 @@ Starts to output preview streams. This API uses an asynchronous callback to retu | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -1931,6 +2349,14 @@ Starts to output preview streams. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | + **Example** ```js @@ -2005,6 +2431,14 @@ Releases output resources. This API uses an asynchronous callback to return the | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2031,6 +2465,14 @@ Releases output resources. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2053,8 +2495,8 @@ Listens for preview frame start events. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | --------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the preview on the first frame starts. This event can be listened for only when a **previewOutput** instance is created.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.| +| callback | AsyncCallback | Yes | Callback used to return the result. The preview starts as long as this event is returned. | **Example** @@ -2076,8 +2518,8 @@ Listens for preview frame end events. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the preview on the last frame ends. This event can be listened for only when a **previewOutput** instance is created.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the last frame of preview ends.| +| callback | AsyncCallback | Yes | Callback used to return the result. The preview ends as long as this event is returned. | **Example** @@ -2097,9 +2539,9 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **PreviewOutput** API, for example, **start()** or **release()**.| +| Name | Type | Mandatory| Description | +| -------- | --------------| ---- | ------------------------ | +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as **start()** or **release()**.| | callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | **Example** @@ -2179,6 +2621,15 @@ Captures a photo with the default shooting parameters. This API uses an asynchro | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2205,6 +2656,15 @@ Captures a photo with the default shooting parameters. This API uses a promise t | -------------- | ------------------------ | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2230,6 +2690,16 @@ Captures a photo with the specified shooting parameters. This API uses an asynch | setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2273,6 +2743,15 @@ Captures a photo with the specified shooting parameters. This API uses a promise | -------------- | ------------------------ | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | **Example** @@ -2318,6 +2797,14 @@ Releases output resources. This API uses an asynchronous callback to return the | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2344,6 +2831,14 @@ Releases output resources. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2366,7 +2861,7 @@ Listens for shooting start events. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The callback function returns the shooting start event.| +| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure each time a photo is taken.| | callback | AsyncCallback | Yes | Callback used to return the capture ID. | **Example** @@ -2387,10 +2882,10 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | --- | ------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The callback function returns the captured frame information (captureId and time).| -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------- | --- | ------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The event can be listened for when a **photoOutput** instance is created.| +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. A new photographing request can be delivered as long as this event is returned. | **Example** @@ -2411,9 +2906,9 @@ Listens for shooting end events. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The callback function returns the shooting end event.| +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding information is returned when the photographing is complete.| | callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | **Example** @@ -2435,9 +2930,9 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code when an API call fails.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a photographing-related API.| | callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | **Example** @@ -2488,6 +2983,15 @@ Starts video recording. This API uses an asynchronous callback to return the res | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2514,6 +3018,14 @@ Starts video recording. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | **Example** @@ -2589,6 +3101,14 @@ Releases output resources. This API uses an asynchronous callback to return the | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2615,6 +3135,14 @@ Releases output resources. This API uses a promise to return the result. | -------------- | ----------------------- | | Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2637,8 +3165,8 @@ Listens for video recording start events. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ----------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the recording on the first frame of an image starts.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **videoOutput** instance is created. The event is triggered and the corresponding information is returned when the bottom layer starts exposure for the first time.| +| callback | AsyncCallback | Yes | Callback used to return the result. The recording starts as long as this event is returned. | **Example** @@ -2660,8 +3188,8 @@ Listens for video recording stop events. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the recording on the last frame of an image stops.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and returned when the last frame of recording is complete.| +| callback | AsyncCallback | Yes | Callback used to return the result. The recording ends as long as this event is returned. | **Example** @@ -2681,9 +3209,9 @@ Listens for errors that occur during video recording. This API uses a callback t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **VideoOutput** API, for example, **start()** or **release()**.| +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a recording-related API such as **start()** and **release()**.| | callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | **Example** @@ -2712,6 +3240,15 @@ Starts to output metadata. This API uses an asynchronous callback to return the | -------- | -------------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2738,6 +3275,15 @@ Starts to output metadata. This API uses a promise to return the result. | ---------------------- | ------------------------ | | Promise | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +**Error codes** + +For details about the error codes, see [CameraErrorCode](#cameraerrorcode). + +| ID | Error Message | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **Example** ```js @@ -2808,9 +3354,9 @@ Listens for metadata objects. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The callback function returns the valid metadata. This event can be listened for only when a **MetadataOutput** instance is created.| +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding metadata is returned when valid metadata is detected.| | callback | Callback\> | Yes | Callback used to return the metadata.| **Example** @@ -2831,9 +3377,9 @@ Listens for metadata errors. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | --------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **MetadataOutput** instance API, for example, **start()** or **release()**.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a metadata-related API such as **start()** and **release()**.| | callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | **Example** @@ -2852,7 +3398,7 @@ Enumerates the metadata object types. | Name | Value | Description | | ------------------------- | ---- | ----------------- | -| FACE_DETECTION | 0 | Face detection.| +| FACE_DETECTION | 0 | Face detection. The detection point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}.
The coordinate system is based on the horizontal device direction with the device's charging port on the right.
If the layout of a preview screen of an application is based on the vertical direction with the charging port on the lower side,
the layout width and height are {w, h} and the return point is {x, y}, then the coordinate point after conversion is {1-y, x}.| ## Rect diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md index cf334f6fd36fd654c2c9558865b0c9f06b68d9ef..9b4aac5ba2690b202ed83cf6386fff3394017ca3 100644 --- a/en/application-dev/reference/apis/js-apis-cert.md +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -104,6 +104,11 @@ Creates an **X509Cert** instance. This API uses an asynchronous callback to retu | inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cert** instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | Memory error. | **Example** @@ -146,6 +151,12 @@ Creates an **X509Cert** instance. This API uses a promise to return the result. | ------- | ---------------- | | Promise\ | **X509Cert** instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | Memory error. | + **Example** ```js @@ -184,6 +195,11 @@ Verifies the certificate signature. This API uses an asynchronous callback to re | key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 19030001 | Crypto operation error. | **Example** @@ -235,6 +251,12 @@ Verifies the certificate signature. This API uses a promise to return the result | -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -275,6 +297,13 @@ Obtains the serialized X.509 certificate data. This API uses an asynchronous cal | -------- | --------------------------------------------- | ---- | -------------------------------- | | callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| **Example** @@ -318,6 +347,14 @@ Obtains the serialized X.509 certificate data. This API uses a promise to return | --------------------------------------- | ---------------------- | | Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -356,6 +393,13 @@ Obtains the public key of this X.509 certificate. This API uses an asynchronous | ------ | ---------------- | | cryptoFramework.PubKey | Public key of the X509 certificate obtained. This object is used only for **verify()** of **X509Cert**.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -398,6 +442,15 @@ Checks the validity period of this X.509 certificate. This API uses an asynchron | -------- | -------------- | ---- | ---------- | | date | string | Yes | Date in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The date must end with **Z**, which indicates the UTC.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error.| +| 19030003 | The certificate has not taken effect. | +| 19030004 | The certificate has expired.| + **Example** ```js @@ -513,6 +566,14 @@ Obtains the X.509 certificate issuer. | --------------------- | ---------------------- | | [DataBlob](#datablob) | X.509 certificate issuer obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -549,6 +610,14 @@ Obtains the subject of this X.509 certificate. | --------------------- | -------------------- | | [DataBlob](#datablob) | Subject name obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -585,6 +654,14 @@ Obtains the start time of this X.509 certificate. | ------ | ------------------------------------------------------------ | | string | Start time of the X509 certificate validity period, in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The value must end with **Z**, which indicates the UTC.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -621,6 +698,14 @@ Obtains the expiration time of this X.509 certificate. | ------ | ------------------------------------------------------------ | | string | Expiration time of the X509 certificate validity period, in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The value must end with **Z**, which indicates the UTC.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -657,6 +742,14 @@ Obtains the signature data of this X.509 certificate. | --------------------- | -------------------- | | [DataBlob](#datablob) | Signature data obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -693,6 +786,14 @@ Obtains the signing algorithm of this X.509 certificate. | ------ | ------------------------ | | string | X.509 certificate signing algorithm obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -729,6 +830,14 @@ Obtains the object identifier (OID) of the X.509 certificate signing algorithm. | ------ | --------------------------------- | | string | OID obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -765,6 +874,14 @@ Obtains the signing algorithm parameters of this X.509 certificate. | --------------------- | ------------------------ | | [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -801,6 +918,13 @@ Obtains the key usage of this X.509 certificate. | --------------------- | -------------------- | | [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -837,6 +961,14 @@ Obtains the usage of the extended key of this X.509 certificate. | ----------------------- | ------------------------ | | [DataArray](#dataarray) | Usage of the extended key obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -909,6 +1041,14 @@ Obtains the Subject Alternative Names (SANs) of this X.509 certificate. | ----------------------- | ------------------------ | | [DataArray](#dataarray) | SANs obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -945,6 +1085,14 @@ Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. | ----------------------- | -------------------------- | | [DataArray](#dataarray) | IANs obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error.| + **Example** ```js @@ -982,6 +1130,11 @@ Creates an **X509Crl** instance. This API uses an asynchronous callback to retur | inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | Memory error. | **Example** @@ -1024,6 +1177,12 @@ Creates an **X509Crl** instance. This API uses a promise to return the result. | ----------------- | -------------------- | | Promise\ | Promise used to return the **X509Crl** instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | Memory error. | + **Example** ```js @@ -1145,6 +1304,13 @@ Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to | -------- | ---------------------------- | ---- | ------------------------------------------ | | callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | **Example** @@ -1188,6 +1354,14 @@ Obtains the serialized X.509 CRL data. This API uses a promise to return the res | ---------------------- | -------------------------------- | | Promise\ | Promise used to return the serialized X.509 CRL data obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1227,6 +1401,11 @@ Verifies the signature of the X.509 CRL. This API uses an asynchronous callback | key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19030001 | Crypto operation error. | **Example** @@ -1279,6 +1458,12 @@ Verifies the signature of the X.509 CRL. This API uses a promise to return the r | ---- | ------------------------------------------------------------ | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1356,6 +1541,14 @@ Obtains the issuer of the X.509 CRL. | --------------------- | ------------------------------ | | [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1392,6 +1585,14 @@ Obtains the date when the X.509 CRL was last updated. | ------ | ------------------------------------ | | string | Last update date of the X.509 CRL.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1428,6 +1629,14 @@ Obtains the date when the CRL will be updated the next time. | ------ | ------------------------------------ | | string | Next update date obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1470,6 +1679,13 @@ Obtains the revoked X.509 certificate based on the specified serial number of th | ---------------------- | --------------------- | | X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1518,6 +1734,13 @@ Obtains the revoked X.509 certificate based on the specified certificate. This A | ------------ | -------------------- | | X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1560,6 +1783,12 @@ Obtains all the revoked X.509 certificates. This API uses an asynchronous callba | -------- | ----------------------------------- | ---- | -------------------------------- | | callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error. | **Example** @@ -1603,6 +1832,13 @@ Obtains all the revoked X.509 certificates. This API uses a promise to return th | ----------------------------- | ---------------------- | | Promise> | Promise used to return a list of revoked X.509 certificates.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1641,6 +1877,14 @@ Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This | --------------------- | ------------------------------- | | [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1681,6 +1925,14 @@ Obtains the signature data of the X.509 CRL. | --------------------- | ------------------------------ | | [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1717,6 +1969,14 @@ Obtains the signing algorithm of the X.509 CRL. | ------ | -------------------------------- | | string | Signing algorithm obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1753,6 +2013,14 @@ Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the In | ------ | --------------------------------------------- | | string | OID of the X.509 CRL signing algorithm obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1789,6 +2057,14 @@ Obtains the parameters of the X.509 CRL signing algorithm. | --------------------- | ---------------------------------- | | [DataBlob](#datablob) | Algorithm parameters obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1831,6 +2107,14 @@ Creates a **CertChainValidator** object. | ------------------ | -------------------- | | CertChainValidator | **CertChainValidator** object created.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -1846,7 +2130,7 @@ Provides APIs for certificate chain validator operations. ### Attributes -**System capability**: SystemCapability.Security.CryptoFramework +**System capability**: SystemCapability.Security.Cert | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------------------- | @@ -1869,6 +2153,19 @@ The certificate chain validator does not verify the certificate validity period | certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | +| 19030002 | The certificate signature verification failed. | +| 19030003 | The certificate has not taken effect. | +| 19030004 | The certificate has expired. | +| 19030005 | Failed to obtain the certificate issuer. | +| 19030006 | The key cannot be used for signing a certificate. | +| 19030007 | The key cannot be used for digital signature. | **Example** @@ -1916,6 +2213,20 @@ The certificate chain validator does not verify the certificate validity period | -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | +| 19030002 | The certificate signature verification failed. | +| 19030003 | The certificate has not taken effect. | +| 19030004 | The certificate has expired. | +| 19030005 | Failed to obtain the certificate issuer. | +| 19030006 | The key cannot be used for signing a certificate. | +| 19030007 | The key cannot be used for digital signature. | + **Example** ```js @@ -1980,6 +2291,13 @@ Obtains the serialized data of this revoked certificate. This API uses an asynch | -------- | --------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | **Example** @@ -2011,6 +2329,14 @@ Obtains the serialized data of this revoked certificate. This API uses a promise | --------------------------------------- | -------------------------- | | Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js @@ -2063,6 +2389,13 @@ Obtains the issuer of this revoked certificate. This API uses an asynchronous ca | --------------------- | ----------------------- | | [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.| +**Error codes** + +| ID| Error Message | +| -------- | -------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | + **Example** ```js @@ -2091,6 +2424,14 @@ Obtains the date when the certificate was revoked. This API uses an asynchronous | ------ | ------------------ | | string | Promise used to return the certificate revocation date obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | Memory error. | +| 19020002 | Runtime error. | +| 19030001 | Crypto operation error. | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-charger.md b/en/application-dev/reference/apis/js-apis-charger.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4f5dba51054c51fd2c74cc1867413340b9a687 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-charger.md @@ -0,0 +1,30 @@ +# @ohos.charger (Charging Type) + +The **charger** module enumerates charging types. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```js +import charger from '@ohos.charger'; +``` + +## ChargeType + +Enumerates charging types. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value | Description | +| -------- | ---- | ----------------- | +| NONE | 0 | Unknown charging type. | +| WIRED_NORMAL | 1 | Wired normal charging.| +| WIRED_QUICK | 2 | Wired fast charging. | +| WIRED_SUPER_QUICK | 3 | Wired super fast charging.| +| WIRELESS_NORMAL | 4 | Wireless normal charging.| +| WIRELESS_QUICK | 5 | Wireless fast charging.| +| WIRELESS_SUPER_QUICK | 6 | Wireless super fast charging.| diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 613913c3635b0f4d4c235e02428faf9a18b9f4b0..1496c18abf062e412dcc36368d046992b7f95c69 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -67,7 +67,7 @@ Publishes a common event with given attributes. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. | -| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| | callback | syncCallback\ | Yes | Callback used to return the result. | **Example** @@ -76,8 +76,8 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ```ts // Attributes of a common event. let options = { - code: 0, // Initial code of the common event. - data: "initial data";// Initial data of the common event. + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. isOrdered: true // The common event is an ordered one. } @@ -151,7 +151,7 @@ Publishes a common event with given attributes to a specific user. This API uses | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. | | userId | number | Yes| User ID.| -| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -194,8 +194,8 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory| Description | | ------------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | -| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.| **Example** @@ -236,12 +236,12 @@ Creates a subscriber. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------- | ----------------------------------------------------- | ---- | -------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information.| **Return value** | Type | Description | | --------------------------------------------------------- | ---------------- | -| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | Promise used to return the subscriber object.| +| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.| **Example** @@ -276,8 +276,8 @@ Subscribes to common events. This API uses an asynchronous callback to return th | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | -------------------------------- | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback used to return the result.| **Example** @@ -299,11 +299,12 @@ function subscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); + subscriber = commonEventSubscriber; // Subscribe to a common event. CommonEvent.subscribe(subscriber, subscribeCB); } @@ -327,7 +328,7 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ---------- | ----------------------------------------------- | ---- | ------------------------ | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | | callback | AsyncCallback\ | No | Callback used to return the result.| **Example** @@ -376,800 +377,3 @@ CommonEvent.createSubscriber(subscribeInfo, createCB); // Unsubscribe from the common event. CommonEvent.unsubscribe(subscriber, unsubscribeCB); ``` - -## CommonEventSubscriber - -### getCode - -```ts -getCode(callback: AsyncCallback): void -``` - -Obtains the code of this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Common event code.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result code obtaining of an ordered common event. -function getCodeCB(err, Code) { - if (err.code) { - console.error(`getCode failed, code is ${err.code}`); - } else { - console.info("getCode " + JSON.stringify(Code)); - } -} -subscriber.getCode(getCodeCB); -``` - -### getCode - -```ts -getCode(): Promise -``` - -Obtains the code of this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Common event code.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getCode().then((code) => { - console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { - console.error(`getCode failed, code is ${err.code}`); -}); -``` - -### setCode - -```ts -setCode(code: number, callback: AsyncCallback): void -``` - -Sets the code for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Common event code. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result code setting of an ordered common event. -function setCodeCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}`); - } else { - console.info("setCode"); - } -} -subscriber.setCode(1, setCodeCB); -``` - -### setCode - -```ts -setCode(code: number): Promise -``` - -Sets the code for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| code | number | Yes | Common event code.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setCode(1).then(() => { - console.info("setCode"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}`); -}); -``` - -### getData - -```ts -getData(callback: AsyncCallback): void -``` - -Obtains the data of this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Common event data.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result data obtaining of an ordered common event. -function getDataCB(err, data) { - if (err.code) { - console.error(`getData failed, code is ${err.code}`); - } else { - console.info("getData " + JSON.stringify(data)); - } -} - -subscriber.getData(getDataCB); -``` - -### getData - -```ts -getData(): Promise -``` - -Obtains the data of this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | ------------------ | -| Promise\ | Common event data.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getData().then((data) => { - console.info("getData " + JSON.stringify(data)); -}).catch((err) => { - console.error(`getData failed, code is ${err.code}`); -}); -``` - -### setData - -```ts -setData(data: string, callback: AsyncCallback): void -``` - -Sets the data for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| data | string | Yes | Common event data. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result data setting of an ordered common event -function setDataCB(err) { - if (err.code) { - console.error(`sendData failed, code is ${err.code}`); - } else { - console.info("setData"); - } -} -subscriber.setData("publish_data_changed", setDataCB); -``` - -### setData - -```ts -setData(data: string): Promise -``` - -Sets the data for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| data | string | Yes | Common event data.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setData("publish_data_changed").then(() => { - console.info("setData"); -}).catch((err) => { - console.error(`setData failed, code is ${err.code}`); -}); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string, callback:AsyncCallback): void -``` - -Sets the code and data for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Common event code. | -| data | string | Yes | Common event data. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result code and result data setting of an ordered common event. -function setCodeDataCB(err) { - if (err.code) { - console.error(`setCodeAndData failed, code is ${err.code}`); - } else { - console.info("setCodeDataCallback"); - } -} - -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string): Promise -``` - -Sets the code and data for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| code | number | Yes | Common event code.| -| data | string | Yes | Common event data.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setCodeAndData(1, "publish_data_changed").then(() => { - console.info("setCodeAndData"); -}).catch((err) => { - console.error(`setCodeAndData failed, code is ${err.code}`); -}); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Returns **true** if the common event is an ordered one; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is an ordered one. -function isOrderedCB(err, isOrdered) { - if (err.code) { - console.error(`isOrderedCommonEvent failed, code is ${err.code}`); - } else { - console.info("isOrdered " + JSON.stringify(isOrdered)); - } -} -subscriber.isOrderedCommonEvent(isOrderedCB); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(): Promise -``` - -Checks whether this common event is an ordered one. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | -------------------------------- | -| Promise\ | Returns **true** if the common event is an ordered one; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.isOrderedCommonEvent().then((isOrdered) => { - console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { - console.error(`isOrderedCommonEvent failed, code is ${err.code}`); -}); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Returns **true** if the common event is a sticky one; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is a sticky one. -function isStickyCB(err, isSticky) { - if (err.code) { - console.error(`isStickyCommonEvent failed, code is ${err.code}`); - } else { - console.info("isSticky " + JSON.stringify(isSticky)); - } -} -subscriber.isStickyCommonEvent(isStickyCB); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(): Promise -``` - -Checks whether this common event is a sticky one. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | -------------------------------- | -| Promise\ | Returns **true** if the common event is a sticky one; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.isStickyCommonEvent().then((isSticky) => { - console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { - console.error(`isSticky failed, code is ${err.code}`); -}); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(callback: AsyncCallback): void -``` - -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for common event aborting. -function abortCB(err) { - if (err.code) { - console.error(`abortCommonEvent failed, code is ${err.code}`); - } else { - console.info("abortCommonEvent"); - } -} - -subscriber.abortCommonEvent(abortCB); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(): Promise -``` - -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.abortCommonEvent().then(() => { - console.info("abortCommonEvent"); -}).catch((err) => { - console.error(`abortCommonEvent failed, code is ${err.code}`); -}); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(callback: AsyncCallback): void -``` - -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for clearing the aborted state of the current common event. -function clearAbortCB(err) { - if (err.code) { - console.error(`clearAbortCommonEvent failed, code is ${err.code}`); - } else { - console.info("clearAbortCommonEvent"); - } -} - -subscriber.clearAbortCommonEvent(clearAbortCB); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(): Promise -``` - -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.clearAbortCommonEvent().then(() => { - console.info("clearAbortCommonEvent"); -}).catch((err) => { - console.error(`clearAbortCommonEvent failed, code is ${err.code}`); -}); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is in the aborted state. -function getAbortCB(err, abortEvent) { - if (err.code) { - console.error(`getAbortCommonEvent failed, code is ${err.code}`); - } else { - console.info("abortEvent " + abortEvent) - } -} - -subscriber.getAbortCommonEvent(getAbortCB); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(): Promise -``` - -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | ---------------------------------- | -| Promise\ | Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getAbortCommonEvent().then((abortCommonEvent) => { - console.info("abortCommonEvent " + JSON.stringify(abortCommonEvent)); -}).catch((err) => { - console.error(`getAbortCommonEvent failed, code is ${err.code}`); -}); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(callback: AsyncCallback): void -``` - -Obtains the subscriber information. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Promise used to return the subscriber information.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for subscriber information obtaining. -function getCB(err, subscribeInfo) { - if (err.code) { - console.error(`getSubscribeInfo failed, code is ${err.code}`); - } else { - console.info("SubscribeInfo " + JSON.stringify(subscribeInfo)); - } -} - -subscriber.getSubscribeInfo(getCB); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(): Promise -``` - -Obtains the subscriber information. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | ---------------------- | -| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Promise used to return the subscriber information.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getSubscribeInfo().then((subscribeInfo) => { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { - console.error(`getSubscribeInfo failed, code is ${err.code}`); -}); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(callback: AsyncCallback): void -``` - -Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for ordered common event finishing. -function finishCB(err) { - if (err.code) { - console.error(`finishCommonEvent failed, code is ${err.code}`); - } else { - console.info("FinishCommonEvent"); - } -} - -subscriber.finishCommonEvent(finishCB); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(): Promise -``` - -Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.finishCommonEvent().then(() => { - console.info("FinishCommonEvent"); -}).catch((err) => { - console.error(`finishCommonEvent failed, code is ${err.code}`); -}); -``` - -## CommonEventData - -Describes the common event data body. - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | -| event | string | Yes | No | Name of the common event that is being received. | -| bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | -| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | - - -## CommonEventPublishData - -Describes the data body published by a common event, including the common event content and attributes. - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| --------------------- | -------------------- | ---- | ---- | ---------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Result code of the common event. | -| data | string | Yes | No | Custom result data of the common event.| -| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | -| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | -| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| -| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | - -## CommonEventSubscribeInfo - -Provides the subscriber information. - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | Yes | No | Name of the common event to publish. | -| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | -| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | -| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index bdcc1af2a479d300303a8d9f851f07c81c3e7d5a..c94524533f8795ee22ebb328ce7ecd1f2ce1ad2c 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -74,7 +74,7 @@ Publishes a common event with given attributes. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. | -| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| | callback | syncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -86,8 +86,8 @@ For details about the error codes, see [Event Error Codes](../errorcodes/errorco ```ts // Attributes of a common event. let options = { - code: 0, // Initial code of the common event. - data: "initial data";// Initial data of the common event. + code: 0, // Result code of the common event. + data: "initial data",// Result data of the common event. isOrdered: true // The common event is an ordered one. } @@ -173,7 +173,7 @@ Publishes a common event with given attributes to a specific user. This API uses | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. | | userId | number | Yes| User ID.| -| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -186,8 +186,8 @@ For details about the error codes, see [Event Error Codes](../errorcodes/errorco ```ts // Attributes of a common event. let options = { - code: 0, // Initial code of the common event. - data: "initial data";// Initial data of the common event. + code: 0, // Result code of the common event. + data: "initial data",// Result data of the common event. } // Callback for common event publication. @@ -224,8 +224,8 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory| Description | | ------------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | -| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.| **Example** @@ -270,12 +270,12 @@ Creates a subscriber. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------- | ----------------------------------------------------- | ---- | -------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information.| **Return value** | Type | Description | | --------------------------------------------------------- | ---------------- | -| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | Promise used to return the subscriber object.| +| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.| **Example** @@ -311,8 +311,8 @@ Subscribes to common events. This API uses an asynchronous callback to return th | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | -------------------------------- | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback used to return the result.| **Example** @@ -327,7 +327,7 @@ let subscribeInfo = { // Callback for common event subscription. function SubscribeCB(err, data) { - if (err.code) { + if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe "); @@ -335,9 +335,10 @@ function SubscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if(!err) { console.info("createSubscriber"); + subscriber = commonEventSubscriber; // Subscribe to a common event. try { CommonEventManager.subscribe(subscriber, SubscribeCB); @@ -371,7 +372,7 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ---------- | ----------------------------------------------- | ---- | ------------------------ | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | | callback | AsyncCallback\ | No | Callback used to return the result.| **Example** @@ -391,11 +392,12 @@ function subscribeCB(err, data) { } } // Callback for subscriber creation. -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if (err) { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { console.info("createSubscriber"); + subscriber = commonEventSubscriber; // Subscribe to a common event. try { CommonEventManager.subscribe(subscriber, subscribeCB); @@ -426,785 +428,3 @@ try { console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } ``` - -## CommonEventSubscriber - -### getCode - -```ts -getCode(callback: AsyncCallback): void -``` - -Obtains the code of this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Common event code.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for code obtaining of an ordered common event. -function getCodeCB(err, code) { - if (err.code) { - console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("getCode " + JSON.stringify(code)); - } -} -subscriber.getCode(getCodeCB); -``` - -### getCode - -```ts -getCode(): Promise -``` - -Obtains the code of this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Common event code.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getCode().then((code) => { - console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { - console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setCode - -```ts -setCode(code: number, callback: AsyncCallback): void -``` - -Sets the code for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Common event code. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for code setting of an ordered common event. -function setCodeCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setCode"); - } -} -subscriber.setCode(1, setCodeCB); -``` - -### setCode - -```ts -setCode(code: number): Promise -``` - -Sets the code for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| code | number | Yes | Common event code.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setCode(1).then(() => { - console.info("setCode"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getData - -```ts -getData(callback: AsyncCallback): void -``` - -Obtains the data of this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Common event data.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for data obtaining of an ordered common event. -function getDataCB(err, data) { - if (err.code) { - console.error(`getData failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("getData " + JSON.stringify(data)); - } -} -subscriber.getData(getDataCB); -``` - -### getData - -```ts -getData(): Promise -``` - -Obtains the data of this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | ------------------ | -| Promise\ | Common event data.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getData().then((data) => { - console.info("getData " + JSON.stringify(data)); -}).catch((err) => { - console.error(`getData failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setData - -setData(data: string, callback: AsyncCallback\): void - -Sets the data for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| data | string | Yes | Common event data. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for result data setting of an ordered common event -function setDataCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setData"); - } -} -subscriber.setData("publish_data_changed", setDataCB); -``` - -### setData - -```ts -setData(data: string): Promise -``` - -Sets the data for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| data | string | Yes | Common event data.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setData("publish_data_changed").then(() => { - console.info("setData"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string, callback:AsyncCallback): void -``` - -Sets the code and data for this common event. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Common event code. | -| data | string | Yes | Common event data. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for code and data setting of an ordered common event. -function setCodeDataCB(err) { - if (err.code) { - console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setCodeDataCallback"); - } -} -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string): Promise -``` - -Sets the code and data for this common event. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| code | number | Yes | Common event code.| -| data | string | Yes | Common event data.| - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.setCodeAndData(1, "publish_data_changed").then(() => { - console.info("setCodeAndData"); -}).catch((err) => { - console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is an ordered one. -function isOrderedCB(err, isOrdered) { - if (err.code) { - console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("isOrdered " + JSON.stringify(isOrdered)); - } -} -subscriber.isOrderedCommonEvent(isOrderedCB); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(): Promise -``` - -Checks whether this common event is an ordered one. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | -------------------------------- | -| Promise\ | Promise used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.isOrderedCommonEvent().then((isOrdered) => { - console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { - console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is a sticky one. -function isStickyCB(err, isSticky) { - if (err.code) { - console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("isSticky " + JSON.stringify(isSticky)); - } -} -subscriber.isStickyCommonEvent(isStickyCB); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(): Promise -``` - -Checks whether this common event is a sticky one. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | -------------------------------- | -| Promise\ | Promise used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.isStickyCommonEvent().then((isSticky) => { - console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { - console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(callback: AsyncCallback): void -``` - -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for common event aborting. -function abortCB(err) { - if (err.code) { - console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("abortCommonEvent"); - } -} -subscriber.abortCommonEvent(abortCB); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(): Promise -``` - -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.abortCommonEvent().then(() => { - console.info("abortCommonEvent"); -}).catch((err) => { - console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(callback: AsyncCallback): void -``` - -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for clearing the aborted state of the current common event. -function clearAbortCB(err) { - if (err.code) { - console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("clearAbortCommonEvent"); - } -} -subscriber.clearAbortCommonEvent(clearAbortCB); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(): Promise -``` - -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.clearAbortCommonEvent().then(() => { - console.info("clearAbortCommonEvent"); -}).catch((err) => { - console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(callback: AsyncCallback): void -``` - -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for checking whether the current common event is in the aborted state. -function getAbortCB(err, abortEvent) { - if (err.code) { - console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("abortCommonEvent " + abortEvent) - } -} -subscriber.getAbortCommonEvent(getAbortCB); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(): Promise -``` - -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ----------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getAbortCommonEvent().then((abortEvent) => { - console.info("abortCommonEvent " + JSON.stringify(abortEvent)); -}).catch((err) => { - console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(callback: AsyncCallback): void -``` - -Obtains the subscriber information. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for subscriber information obtaining. -function getCB(err, subscribeInfo) { - if (err.code) { - console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); - } -} -subscriber.getSubscribeInfo(getCB); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(): Promise -``` - -Obtains the subscriber information. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | ---------------------- | -| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Promise used to return the subscriber information.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.getSubscribeInfo().then((subscribeInfo) => { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { - console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(callback: AsyncCallback): void -``` - -Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -// Callback for ordered common event finishing. -function finishCB(err) { - if (err.code) { - console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); -} else { - console.info("FinishCommonEvent"); -} - -subscriber.finishCommonEvent(finishCB); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(): Promise -``` - -Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. - -**System capability**: SystemCapability.Notification.CommonEvent - -**Return value** - -| Type | Description | -| ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -let subscriber; // Subscriber object successfully created. - -subscriber.finishCommonEvent().then(() => { - console.info("FinishCommonEvent"); -}).catch((err) => { - console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -## CommonEventData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | -| event | string | Yes | No | Name of the common event that is being received. | -| bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Code of the common event, which is used to transfer data of the int type. | -| data | string | Yes | No | Custom data of the common event, which is used to transfer data of the string type.| -| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | - - -## CommonEventPublishData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| --------------------- | -------------------- | ---- | ---- | ---------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Code of the common event. | -| data | string | Yes | No | Custom data of the common event.| -| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | -| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | -| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| -| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | - -## CommonEventSubscribeInfo - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Type | Readable| Writable| Description | -| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | Yes | No | Name of the common event to publish. | -| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | -| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | -| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index 2778a143c65125eca650324e67a220ab60f64ead..bcc8b36fc9a93191258ed78edb68df61ccce4c28 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -166,6 +166,7 @@ Updates a contact based on the specified contact information. This API uses an a ```js contact.updateContact({ + id: 1, name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, (err) => { @@ -200,6 +201,7 @@ Updates a contact based on the specified contact information and attributes. Thi ```js contact.updateContact({ + id: 1, name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, { @@ -241,6 +243,7 @@ Updates a contact based on the specified contact information and attributes. Thi ```js let promise = contact.updateContact({ + id: 1, name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, { diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 70d35b6cb168e6f10b847a42bdefa8fd53eb3d40..4c66c928fb7ee6c5482d39db7b39acaa6793691e 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -47,21 +47,27 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -let xml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; -let conv = new convertxml.ConvertXML() -let options = {trim : false, declarationKey:"_declaration", - instructionKey : "_instruction", attributesKey : "_attributes", - textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", - commentKey : "_comment", parentKey : "_parent", typeKey : "_type", - nameKey : "_name", elementsKey : "_elements"} -let result = JSON.stringify(conv.convertToJSObject(xml, options)); -console.log(result); +try { + let xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + let conv = new convertxml.ConvertXML() + let options = { + trim: false, declarationKey: "_declaration", + instructionKey: "_instruction", attributesKey: "_attributes", + textKey: "_text", cdataKey: "_cdata", doctypeKey: "_doctype", + commentKey: "_comment", parentKey: "_parent", typeKey: "_type", + nameKey: "_name", elementsKey: "_elements" + } + let result = JSON.stringify(conv.convertToJSObject(xml, options)); + console.log(result); +} catch (e) { + console.log(e.toString()); +} // Output (non-compact) // {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} ``` diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index a92fdd87e5e31b2f7b38345acacbb640ff27212f..afb1bd3f8d80a74415c359af492492286364008c 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -51,7 +51,7 @@ For details about the supported specifications, see [HMAC Algorithm Specificatio | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| **Return value** @@ -483,7 +483,7 @@ For details about the supported specifications, see [MD Algorithm Specifications | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| **Return value** @@ -1852,7 +1852,7 @@ Updates the data to encrypt or decrypt by segment. This API uses a promise to re | Type | Description | | ------------------------------- | ------------------------------------------------ | -| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data). | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| **Error codes** @@ -2174,7 +2174,7 @@ update(data : DataBlob, callback : AsyncCallback\) : void Updates the data to be signed. This API uses an asynchronous callback to return the result. > **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Signing Data and Verifying Signatures](../../security/cryptoFramework-guidelines.md#signing-data-and-verifying-signatures). +> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). **System capability**: SystemCapability.Security.CryptoFramework @@ -2200,7 +2200,7 @@ update(data : DataBlob) : Promise\; Updates the data to be signed. This API uses a promise to return the result. > **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Signing Data and Verifying Signatures](../../security/cryptoFramework-guidelines.md#signing-data-and-verifying-signatures). +> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). **System capability**: SystemCapability.Security.CryptoFramework @@ -2267,6 +2267,8 @@ Signs the data. This API uses a promise to return the result. | -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + | ID| Error Message | | -------- | ---------------------- | | 17620001 | memory error. | @@ -2465,7 +2467,7 @@ update(data : DataBlob, callback : AsyncCallback\) : void Updates the data for signature verification. This API uses an asynchronous callback to return the result. > **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Signing Data and Verifying Signatures](../../security/cryptoFramework-guidelines.md#signing-data-and-verifying-signatures). +> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). **System capability**: SystemCapability.Security.CryptoFramework @@ -2491,7 +2493,7 @@ update(data : DataBlob) : Promise\; Updates the data for signature verification. This API uses a promise to return the result. > **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Signing Data and Verifying Signatures](../../security/cryptoFramework-guidelines.md#signing-data-and-verifying-signatures). +> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). **System capability**: SystemCapability.Security.CryptoFramework diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index cf3067e37fd78e9c9d0f3d701b1fdf30cb79c88f..718c84781a3d2c9b28f9a73de9ed4548027ef09e 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -209,9 +209,10 @@ Curves.responsiveSpringMotion() // Create a responsive spring animation curve wi interpolate(fraction: number): number - Implements calculation. +Since API version 9, this API is supported in ArkTS widgets. + **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index 82a333b14b2ea90e92540ee31142ea884c7f2593..b79161a08e5916eecca479c99f6fd852f8e6fd4a 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,14 +1,15 @@ -# @ohos.data.dataShare (DataShare) +# @ohos.data.dataShare (Data Sharing) The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. > -> The APIs of this module can be used only in the stage model. +> - The APIs provided by this module are system APIs. +> +> - The APIs of this module can be used only in the stage model. ## Modules to Import @@ -55,7 +56,7 @@ Observe the following when using this API: | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. | +| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. | | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| @@ -105,7 +106,7 @@ Observe the following when using this API: | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------- | ---- | ------------------------------ | -| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. | +| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. | | uri | string | Yes | URI of the server application to connect.| **Return value** @@ -187,18 +188,19 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | No | Callback for the data change event. If this parameter is left empty, all notification events of the URI are unsubscribed from.| **Example** ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -function offCallback() { - console.info("**** Observer off callback ****"); +function callback() { + console.info("**** Observer callback ****"); } let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.off("dataChange", uri, offCallback); +dataShareHelper.on("dataChange", uri, callback); +dataShareHelper.off("dataChange", uri, callback); ``` ### insert 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 de22c34d2a99d3e7391061cc9233089409944599..99e43bc6a0e1a748dcea5eb8777db5361ded3040 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -5,7 +5,7 @@ The **Preferences** module provides APIs for processing data in the form of key- The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -22,8 +22,8 @@ import data_preferences from '@ohos.data.preferences'; | Name | Type| Readable| Writable| Description | | ---------------- | -------- | ---- | ---- | --------------------------------------- | -| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key. The key must be less than 80 bytes. | -| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value. The value must be less than 8192 bytes.| +| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. | +| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.| ## data_preferences.getPreferences @@ -38,8 +38,8 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | -| name | string | Yes | Name of the **Preferences** instance.| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.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** @@ -213,7 +213,6 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { try { @@ -289,7 +288,6 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { try{ @@ -350,7 +348,6 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { try { @@ -973,7 +970,7 @@ Unsubscribes from data changes. | 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.| +| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks for all data changes will be unregistered.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index 75e9293eadcd0a25fc923146b92246a885829df6..dbb9244fbe3f973baf0b307a80b7a0ed23482f71 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -7,8 +7,8 @@ The **DataStorage** module provides applications with data processing capability > > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - The APIs of this module are no longer maintained since API version 9. You are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md). -> +> - The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.preferences](js-apis-data-preferences.md). +> > - The APIs of this module can be used only in the FA model. @@ -24,8 +24,8 @@ import data_storage from '@ohos.data.storage'; | Name | Type| Readable| Writable| Description | | ---------------- | -------- | ---- | ---- | ------------------------------------- | -| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key. It must be less than 80 bytes. | -| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value. It must be less than 8192 bytes.| +| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. | +| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.| ## data_storage.getStorageSync @@ -79,7 +79,7 @@ Reads the specified file and loads its data to the **Storage** instance for data | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------- | | path | string | Yes | Path of the target file.| -| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback invoked to return the result. | **Example** @@ -172,7 +172,7 @@ context.getFilesDir().then((filePath) => { console.info("======================>getFilesDirPromise====================>"); data_storage.deleteStorageSync(path + '/mystore'); -}); +}); ``` ## data_storage.deleteStorage @@ -276,9 +276,9 @@ let context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; console.info("======================>getFilesDirPromise====================>"); - + data_storage.removeStorageFromCacheSync(path + '/mystore'); -}); +}); ``` @@ -406,7 +406,7 @@ Obtains the value corresponding to a key. If the value is null or not of the def | -------- | ------------------------------ | ---- | ----------------------------------------- | | key | string | Yes | Key of the data. It cannot be empty. | | defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value.| -| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<ValueType> | Yes | Callback invoked to return the result. | **Example** @@ -581,7 +581,7 @@ Checks whether the storage object contains data with a given key. This API uses | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------- | | key | string | Yes | Key of the data. It cannot be empty.| -| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Return value** @@ -867,7 +867,7 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ------ |---------------------------------------- | | type | string |Yes| Event type. The value **change** indicates data change events.| -| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback used to return data changes. | +| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback invoked to return the data change. | **Example** @@ -894,7 +894,7 @@ Unsubscribes from data changes. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ------ |---------------------------------------- | | type | string |Yes| Event type. The value **change** indicates data change events.| -| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback used to return data changes. | +| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback for the data change. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 60e97b69134e1b1b962fc1f5e67e790a00daea4a..5d6b71b99b23044250b231f34630a973f0705515 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -96,7 +96,7 @@ Enumerates the device types. | CAR | 0x83 | Car. | | UNKNOWN_TYPE | 0 | Unknown device type.| -## AuthForm +## AuthForm10+ Enumerates the device authentication types. @@ -131,12 +131,12 @@ Defines subscription information. | Name | Type | Mandatory | Description | | ------------- | --------------------------------- | ---- | ----------------- | | subscribeId | number | Yes | Subscription ID, used to identify a device discovery period.| -| mode | [DiscoverMode ](#discovermode) | No | Device discovery mode. | -| medium | [ExchangeMedium](#exchangemedium) | No | Medium used for device discovery. | -| freq | [ExchangeFreq](#exchangefreq) | No | Frequency of device discovery. | -| isSameAccount | boolean | No | Whether the same account is used on the discovered device. | -| isWakeRemote | boolean | No | Whether to wake up the discovered device. | -| capability | [SubscribeCap](#subscribecap) | No | Discovery capability. | +| mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. | +| medium | [ExchangeMedium](#exchangemedium) | Yes | Medium used for device discovery. | +| freq | [ExchangeFreq](#exchangefreq) | Yes | Frequency of device discovery. | +| isSameAccount | boolean | Yes | Whether the same account is used on the discovered device. | +| isWakeRemote | boolean | Yes | Whether to wake up the discovered device. | +| capability | [SubscribeCap](#subscribecap) | Yes | Discovery capability. | ## DiscoverMode @@ -262,8 +262,6 @@ getTrustedDeviceListSync(): Array<DeviceInfo> Obtains all trusted devices synchronously. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -296,8 +294,6 @@ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): voi Obtains all trusted devices. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -336,8 +332,6 @@ getTrustedDeviceList(): Promise<Array<DeviceInfo>> Obtains all trusted devices. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -370,8 +364,6 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) Obtains local device information synchronously. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -404,8 +396,6 @@ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void Obtains local device information. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -444,8 +434,6 @@ getLocalDeviceInfo(): Promise<DeviceInfo> Obtains local device information. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -478,8 +466,6 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo): void Starts to discover peripheral devices. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -524,8 +510,6 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void Starts to discover peripheral devices and filters discovered devices. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -580,8 +564,6 @@ stopDeviceDiscovery(subscribeId: number): void Stops device discovery. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -616,8 +598,6 @@ publishDeviceDiscovery(publishInfo: PublishInfo): void Publishes device information for discovery purposes. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -659,8 +639,6 @@ unPublishDeviceDiscovery(publishId: number): void Stops publishing device information. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -695,8 +673,6 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async Authenticates a device. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -757,8 +733,6 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void Deauthenticates a device. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -798,8 +772,6 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, Verifies authentication information. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -844,8 +816,6 @@ setUserOperation(operateAction: number, params: string): void; Sets a user operation. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -874,14 +844,134 @@ Sets a user operation. } ``` +### requestCredentialRegisterInfo10+ + +requestCredentialRegisterInfo(requestInfo: string, callback: AsyncCallback<{registerInfo: string}>): void; + +Obtains the registration information of the credential. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------------- | --------------- | ---- | ------------------- | + | requestInfo | string | Yes | Request credential information. | + | callback | AsyncCallback<{registerInfo: string}> | Yes | Callback used to return the credential registration information.| + +**Example** + + ```js + let credentialInfo = { + "version" : "1.2.3", + "userId" : "123" + } + try { + dmClass.requestCredentialRegisterInfo(credentialInfo, (data) => { + if (data) { + console.info("requestCredentialRegisterInfo result:" + JSON.stringify(data)); + } else { + console.info.push("requestCredentialRegisterInfo result: data is null"); + } + }); + } catch (err) { + console.error("requestCredentialRegisterInfo err:" + err.code + "," + err.message); + } + ``` + +### importCredential10+ + +importCredential(credentialInfo: string, callback: AsyncCallback<{resultInfo: string}>): void; + +Imports credential information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------------- | --------------- | ---- | ------------------- | + | credentialInfo| string | Yes | Credential information to import. | + | callback | AsyncCallback<{resultInfo: string}> | Yes | Callback used to return the result.| + +**Example** + + ```js + let credentialInfo = { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "deviceId" : "aaa", + "version" : "1.2.3", + "devicePk" : "0000", + "credentialData" : + [ + { + "credentialType" : 2, + "credentialId" : "102", + "serverPk" : "3059301306072A8648CE3D020106082A8648CE3D03", + "pkInfoSignature" : "30440220490BCB4F822004C9A76AB8D97F80041FC0E", + "pkInfo" : "", + "authCode" : "", + "peerDeviceId" : "" + } + ] + } + try { + dmClass.importCredential(credentialInfo, (data) => { + if (data) { + console.info("importCredential result:" + JSON.stringify(data)); + } else { + console.info.push("importCredential result: data is null"); + } + }); + } catch (err) { + console.error("importCredential err:" + err.code + "," + err.message); + } + ``` + +### deleteCredential10+ + +deleteCredential(queryInfo: string, callback: AsyncCallback<{resultInfo: string}>): void; + +Deletes credential information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------------- | --------------- | ---- | ------------------- | + | queryInfo | string | Yes | Credential information to delete. | + | callback | AsyncCallback<{resultInfo: string}> | Yes | Callback used to return the result.| + +**Example** + + ```js + let queryInfo = { + "processType" : 1, + "authType" : 1, + "userId" : "123" + } + try { + dmClass.deleteCredential(queryInfo, (data) => { + if (data) { + console.info("deleteCredential result:" + JSON.stringify(data)); + } else { + console.info.push("deleteCredential result: data is null"); + } + }); + } catch (err) { + console.error("deleteCredential err:" + err.code + "," + err.message); + } + ``` + ### on('uiStateChange')9+ on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; Subscribes to UI status changes. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -912,8 +1002,6 @@ off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; Unsubscribes from UI status changes. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -939,8 +1027,6 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange Subscribes to changes in the device state. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -968,8 +1054,6 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang Unsubscribes from changes in the device state. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -997,8 +1081,6 @@ on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: Dev Subscribes to device discovery events. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1026,8 +1108,6 @@ off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: D Unsubscribes from device discovery events. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1055,8 +1135,6 @@ on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: nu Subscribes to device discovery failures. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1084,8 +1162,6 @@ off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: Unsubscribes from device discovery failures. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1113,8 +1189,6 @@ on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): voi Subscribes to device information publication success events. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1143,8 +1217,6 @@ off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): v Unsubscribes from device information publication success events. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1172,8 +1244,6 @@ on(type: 'publishFail', callback: Callback<{ publishId: number, reason: numbe Subscribes to device information publication failures. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1201,8 +1271,6 @@ off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: num Unsubscribes from device information publication failures. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1230,8 +1298,6 @@ on(type: 'serviceDie', callback: () => void): void Subscribes to dead events of the **DeviceManager** service. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1259,8 +1325,6 @@ off(type: 'serviceDie', callback?: () => void): void Unsubscribes from dead events of the **DeviceManager** service. -**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) - **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 7b9ca74c921ecb8590b09df41bd37aa309794257..aa475afa50fe07e03f9a8341b1429a16f7151658 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -28,7 +28,7 @@ Provides the **KVManager** instance configuration, including the bundle name of | Name | Type | Mandatory| Description | | ---------- | --------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes |Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes |Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| | bundleName | string | Yes | Bundle name. | ## Constants @@ -258,7 +258,7 @@ Creates a **KVManager** instance to manage KV stores. | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | --------------------------------------------------------- | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name and user information of the caller.| +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the caller and user information.| **Return value** @@ -271,8 +271,7 @@ Creates a **KVManager** instance to manage KV stores. Stage model: ```js -import UIAbility from '@ohos.app.ability.UIAbility'; - +import UIAbility from '@ohos.app.ability.UIAbility' let kvManager; export default class EntryAbility extends UIAbility { onCreate() { @@ -295,7 +294,7 @@ export default class EntryAbility extends UIAbility { FA model: ```js -import featureAbility from '@ohos.ability.featureAbility'; +import featureAbility from '@ohos.ability.featureAbility' let kvManager; let context = featureAbility.getContext() const kvManagerConfig = { @@ -358,7 +357,7 @@ try { console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log("Obtained the KVStore successfully."); + console.log("Succeeded in getting KVStore"); kvStore = store; }); } catch (e) { @@ -411,7 +410,7 @@ try { securityLevel: distributedKVStore.SecurityLevel.S2, }; kvManager.getKVStore('storeId', options).then((store) => { - console.log("Obtained the KVStore successfully."); + console.log("Succeeded in getting KVStore"); kvStore = store; }).catch((err) => { console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); @@ -453,14 +452,14 @@ const options = { } try { kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('Obtained the KVStore successfully.'); + console.log('Succeeded in getting KVStore'); kvStore = store; kvManager.closeKVStore('appId', 'storeId', function (err, data) { if (err != undefined) { console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the KVStore successfully.'); + console.log('Succeeded in closing KVStore'); }); }); } catch (e) { @@ -505,10 +504,10 @@ const options = { } try { kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('Obtained the KVStore successfully.'); + console.log('Succeeded in getting KVStore'); kvStore = store; kvManager.closeKVStore('appId', 'storeId').then(() => { - console.log('Closed the KVStore successfully.'); + console.log('Succeeded in closing KVStore'); }).catch((err) => { console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); }); @@ -564,14 +563,14 @@ try { console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the KVStore successfully.'); + console.log('Succeeded in getting KVStore'); kvStore = store; kvManager.deleteKVStore('appId', 'storeId', function (err, data) { if (err != undefined) { console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log(`Deleted the KVStore successfully.`); + console.log(`Succeeded in deleting KVStore`); }); }); } catch (e) { @@ -624,10 +623,10 @@ const options = { } try { kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('Obtained the KVStore successfully.'); + console.log('Succeeded in getting KVStore'); kvStore = store; kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('Deleted the KVStore successfully.'); + console.log('Succeeded in deleting KVStore'); }).catch((err) => { console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); }); @@ -664,7 +663,7 @@ try { console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained all KV store IDs successfully.'); + console.log('Succeeded in getting AllKVStoreId'); console.log(`GetAllKVStoreId size = ${data.length}`); }); } catch (e) { @@ -699,7 +698,7 @@ let kvManager; try { console.log('GetAllKVStoreId'); kvManager.getAllKVStoreId('appId').then((data) => { - console.log('Obtained all KV store IDs successfully.'); + console.log('Succeeded in getting AllKVStoreId'); console.log(`GetAllKVStoreId size = ${data.length}`); }).catch((err) => { console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); @@ -829,7 +828,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully.'); + console.log('getResultSet succeeded.'); resultSet = result; }).catch((err) => { console.log('getResultSet failed: ' + err); @@ -1000,7 +999,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); @@ -1039,7 +1038,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); @@ -1242,7 +1241,7 @@ Resets the **Query** object. | Type | Description | | -------------- | --------------------- | -| [Query](query) | **Query** object reset.| +| [Query](#query) | **Query** object reset.| **Example** @@ -1278,7 +1277,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1312,7 +1311,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1345,7 +1344,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1380,7 +1379,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1415,7 +1414,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1450,7 +1449,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1483,7 +1482,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1517,7 +1516,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1551,7 +1550,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1585,7 +1584,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1619,7 +1618,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1653,7 +1652,7 @@ Creates a **Query** object to match the specified field whose value is similar t | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1687,7 +1686,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1714,7 +1713,7 @@ Creates a **Query** object with the AND condition. | Type | Description | | -------------- | -------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1743,7 +1742,7 @@ Creates a **Query** object with the OR condition. | Type | Description | | -------------- | -------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1778,7 +1777,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1812,7 +1811,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1847,7 +1846,7 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1883,7 +1882,7 @@ Creates a **Query** object to match the specified field whose value is not **nul | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1910,7 +1909,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1939,7 +1938,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -1974,7 +1973,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -2008,7 +2007,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -2042,7 +2041,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | -------------- | --------------- | -| [Query](query) | **Query** object created.| +| [Query](#query) | **Query** object created.| **Example** @@ -2125,7 +2124,7 @@ try { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Put data successfully."); + console.log("Succeeded in putting"); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2170,7 +2169,7 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Put data successfully. data=${data}`); + console.log(`Succeeded in putting.data=${data}`); }).catch((err) => { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); }); @@ -2226,12 +2225,12 @@ try { console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -2289,9 +2288,9 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`PutBatch ${entries}`); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); @@ -2349,7 +2348,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }) } catch (e) { console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); @@ -2402,7 +2401,7 @@ try { v8Arr.push(vb2); v8Arr.push(vb3); kvStore.putBatch(v8Arr).then(async (data) => { - console.log(`Batch put data successfully.`); + console.log(`Succeeded in putting patch`); }).catch((err) => { console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); }); @@ -2447,13 +2446,13 @@ try { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); return; } - console.log('Put data successfully.'); + console.log('Succeeded in putting'); kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); return; } - console.log('Deleted data successfully.'); + console.log('Succeeded in deleting'); }); }); } catch (e) { @@ -2498,9 +2497,9 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Put data successfully: ${data}`); + console.log(`Succeeded in putting: ${data}`); kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Deleted data successfully.'); + console.log('Succeeded in deleting'); }).catch((err) => { console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); }); @@ -2547,7 +2546,7 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); kvStore.delete(predicates, function (err, data) { if (err == undefined) { - console.log('Deleted data successfully.'); + console.log('Succeeded in deleting'); } else { console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); } @@ -2599,9 +2598,9 @@ try { let arr = ["name"]; predicates.inKeys(arr); kvStore.put("name", "bob").then((data) => { - console.log(`Put data successfully: ${data}`); + console.log(`Succeeded in putting: ${data}`); kvStore.delete(predicates).then((data) => { - console.log('Deleted data successfully.'); + console.log('Succeeded in deleting'); }).catch((err) => { console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); }); @@ -2662,13 +2661,13 @@ try { console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.deleteBatch(keys, async function (err, data) { if (err != undefined) { console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch deleted data successfully.'); + console.log('Succeeded in deleting Batch'); }); }); } catch (e) { @@ -2726,9 +2725,9 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (data) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.deleteBatch(keys).then((err) => { - console.log('Batch deleted data successfully.'); + console.log('Succeeded in deleting Batch'); }).catch((err) => { console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); }); @@ -2771,15 +2770,15 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { - console.log('Put data successfully.'); + console.log('Succeeded in putting data'); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid, async function (err, data) { if (err == undefined) { - console.log('Removed device data successfully.'); + console.log('succeeded in removing device data'); } else { console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { - console.log('Obtained data successfully.'); + console.log('Succeeded in getting data'); }); } }); @@ -2825,18 +2824,18 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('Put data successfully.'); + console.log('Succeeded in putting data'); }).catch((err) => { console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); }); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid).then((err) => { - console.log('Removed device data successfully.'); + console.log('succeeded in removing device data'); }).catch((err) => { console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); }); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Obtained data successfully.'); + console.log('Succeeded in getting data'); }).catch((err) => { console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); }); @@ -2882,13 +2881,13 @@ try { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Put data successfully."); + console.log("Succeeded in putting"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); return; } - console.log(`Obtained data successfully. data=${data}`); + console.log(`Succeeded in getting data.data=${data}`); }); }); } catch (e) { @@ -2934,9 +2933,9 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Put data successfully. data=${data}`); + console.log(`Succeeded in putting data.data=${data}`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log(`Obtained data successfully. data=${data}`); + console.log(`Succeeded in getting data.data=${data}`); }).catch((err) => { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); }); @@ -2995,13 +2994,13 @@ try { console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -3059,9 +3058,9 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`PutBatch ${entries}`); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); @@ -3086,7 +3085,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ----------------------------------------------- | -| query | [Query](query) | Yes | Key prefix to match. | +| query | [Query](#query) | Yes | Key prefix to match. | | callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| **Error codes** @@ -3118,7 +3117,7 @@ try { } console.log(`entries: {entries}`); kvStore.putBatch(entries, async function (err, data) { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query, function (err, entries) { @@ -3126,7 +3125,7 @@ try { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -3148,7 +3147,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses a | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -3185,18 +3184,18 @@ try { } console.log(`entries: {entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query).then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) }); - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); } catch (e) { console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); } @@ -3249,20 +3248,20 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); kvStore.getResultSet('batch_test_string_key', async function (err, result) { if (err != undefined) { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }) }); }); @@ -3319,18 +3318,18 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -3386,7 +3385,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query, async function (err, result) { @@ -3394,7 +3393,7 @@ try { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); }); }); } catch (e) { @@ -3414,7 +3413,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -3450,14 +3449,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); @@ -3508,14 +3507,14 @@ try { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }) }); } catch (e) { @@ -3565,13 +3564,13 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates).then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -3603,7 +3602,7 @@ try { let resultSet = null; kvStore.closeResultSet(resultSet, function (err, data) { if (err == undefined) { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); } else { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); } @@ -3640,7 +3639,7 @@ let kvStore; try { let resultSet = null; kvStore.closeResultSet(resultSet).then(() => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -3661,7 +3660,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------- | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| **Error codes** @@ -3691,7 +3690,7 @@ try { entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query, async function (err, resultSize) { @@ -3699,7 +3698,7 @@ try { console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set size successfully'); + console.log('Succeeded in getting result set size'); }); }); } catch (e) { @@ -3719,7 +3718,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -3754,14 +3753,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { - console.log('Obtained the result set size successfully'); + console.log('Succeeded in getting result set size'); }).catch((err) => { console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); }); @@ -3803,7 +3802,7 @@ try { if (err) { console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); } else { - console.info(`Backed up data successfully. data=${data}`); + console.info(`Succeeded in backupping data.data=${data}`); } }); } catch (e) { @@ -3846,7 +3845,7 @@ let kvStore; let file = "BK001"; try { kvStore.backup(file).then((data) => { - console.info(`Backed up data successfully. data=${data}`); + console.info(`Succeeded in backupping data.data=${data}`); }).catch((err) => { console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); }); @@ -3888,7 +3887,7 @@ try { if (err) { console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); } else { - console.info(`Restored data successfully. data=${data}`); + console.info(`Succeeded in restoring data.data=${data}`); } }); } catch (e) { @@ -3931,7 +3930,7 @@ let kvStore; let file = "BK001"; try { kvStore.restore(file).then((data) => { - console.info(`Restored data successfully. data=${data}`); + console.info(`Succeeded in restoring data.data=${data}`); }).catch((err) => { console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); }); @@ -3965,7 +3964,7 @@ try { if (err) { console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); } else { - console.info(`Deleted the backup file successfully. data=${data}`); + console.info(`Succeed in deleting Backup.data=${data}`); } }); } catch (e) { @@ -4000,7 +3999,7 @@ let kvStore; let files = ["BK001", "BK002"]; try { kvStore.deleteBackup(files).then((data) => { - console.info(`Deleted the backup file successfully. data=${data}`); + console.info(`Succeed in deleting Backup.data=${data}`); }).catch((err) => { console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); }) @@ -4061,7 +4060,7 @@ try { console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); return; } - console.log('Started the transaction successfully.'); + console.log('Succeeded in starting Transaction'); let entries = putBatchString(10, 'batch_test_string_key'); console.log(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { @@ -4069,7 +4068,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); }); }); } catch (e) { @@ -4110,7 +4109,7 @@ try { count++; }); kvStore.startTransaction().then(async (err) => { - console.log('Started the transaction successfully.'); + console.log('Succeeded in starting Transaction'); }).catch((err) => { console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); }); @@ -4148,7 +4147,7 @@ let kvStore; try { kvStore.commit(function (err, data) { if (err == undefined) { - console.log('Committed the transaction successfully.'); + console.log('Succeeded in committing'); } else { console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); } @@ -4186,7 +4185,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err let kvStore; try { kvStore.commit().then(async (err) => { - console.log('Committed the transaction successfully.'); + console.log('Succeeded in committing'); }).catch((err) => { console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); }); @@ -4224,7 +4223,7 @@ let kvStore; try { kvStore.rollback(function (err,data) { if (err == undefined) { - console.log('Rolled back the transaction successfully'); + console.log('Succeeded in rolling back'); } else { console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); } @@ -4262,7 +4261,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err let kvStore; try { kvStore.rollback().then(async (err) => { - console.log('Rolled back the transaction successfully'); + console.log('Succeeded in rolling back'); }).catch((err) => { console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); }); @@ -4293,7 +4292,7 @@ let kvStore; try { kvStore.enableSync(true, function (err, data) { if (err == undefined) { - console.log('Enabled sync successfully.'); + console.log('Succeeded in enabling sync'); } else { console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); } @@ -4329,7 +4328,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses a pro let kvStore; try { kvStore.enableSync(true).then((err) => { - console.log('Enabled sync successfully.'); + console.log('Succeeded in enabling sync'); }).catch((err) => { console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); }); @@ -4366,7 +4365,7 @@ try { console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); return; } - console.log('Set syncRange successfully.'); + console.log('Succeeded in setting syncRange'); }); } catch (e) { console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); @@ -4402,7 +4401,7 @@ try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('Set syncRange successfully.'); + console.log('Succeeded in setting syncRange'); }).catch((err) => { console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); }); @@ -4437,7 +4436,7 @@ try { console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); return; } - console.log('Set syncParam successfully'); + console.log('Succeeded in setting syncParam'); }); } catch (e) { console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); @@ -4471,7 +4470,7 @@ let kvStore; try { const defaultAllowedDelayMs = 500; kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('Set syncParam successfully'); + console.log('Succeeded in setting syncParam'); }).catch((err) => { console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); }); @@ -4522,7 +4521,7 @@ try { console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); return; } - console.log('Put data successfully.'); + console.log('Succeeded in putting data'); const devices = ['deviceList']; const mode = distributedKVStore.SyncMode.PULL_ONLY; kvStore.sync(devices, mode, 1000); @@ -4548,7 +4547,7 @@ Synchronizes the KV store manually. This API returns the result synchronously. F | --------- | --------------------- | ---- | ---------------------------------------------- | | deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | delayMs | number | No | Allowed synchronization delay time, in ms. | **Error codes** @@ -4575,7 +4574,7 @@ try { console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); return; } - console.log('Put data successfully.'); + console.log('Succeeded in putting data'); const devices = ['deviceList']; const mode = distributedKVStore.SyncMode.PULL_ONLY; const query = new distributedKVStore.Query(); @@ -4652,7 +4651,7 @@ try { console.log(`syncComplete ${data}`); }); kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('Put data successfully.'); + console.log('succeeded in putting'); }).catch((err) => { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); }); @@ -4793,7 +4792,7 @@ try { console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained securityLevel successfully'); + console.log('Succeeded in getting securityLevel'); }); } catch (e) { console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); @@ -4828,7 +4827,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err let kvStore; try { kvStore.getSecurityLevel().then((data) => { - console.log('Obtained securityLevel successfully'); + console.log('Succeeded in getting securityLevel'); }).catch((err) => { console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); }); @@ -4884,13 +4883,13 @@ try { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Put data successfully."); + console.log("Succeeded in putting"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); return; } - console.log(`Obtained data successfully. data=${data}`); + console.log(`Succeeded in getting data.data=${data}`); }); }); } catch (e) { @@ -4936,9 +4935,9 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Put data successfully. data=${data}`); + console.log(`Succeeded in putting data.data=${data}`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log(`Obtained data successfully. data=${data}`); + console.log(`Succeeded in getting data.data=${data}`); }).catch((err) => { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); }); @@ -4988,13 +4987,13 @@ try { console.error(`Fail to put.code is ${err.code},message is ${err.message}`); return; } - console.log('Put data successfully.'); + console.log('Succeeded in putting'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained data successfully'); + console.log('Succeeded in getting'); }); }) } catch (e) { @@ -5041,9 +5040,9 @@ const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log('Put data successfully.'); + console.log('Succeeded in putting'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Obtained data successfully'); + console.log('Succeeded in getting'); }).catch((err) => { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); }); @@ -5102,13 +5101,13 @@ try { console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -5166,9 +5165,9 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`PutBatch ${entries}`); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); @@ -5229,13 +5228,13 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { if (err != undefined) { console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -5294,9 +5293,9 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); console.log(`entries[0].value: ${entries[0].value}`); @@ -5324,7 +5323,7 @@ Obtains all KV pairs that match the specified **Query** object for this device. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ----------------------------------------------------- | -| query | [Query](query) | Yes | Key prefix to match. | +| query | [Query](#query) | Yes | Key prefix to match. | | callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| **Error codes** @@ -5356,7 +5355,7 @@ try { } console.log(`entries: {entries}`); kvStore.putBatch(entries, async function (err, data) { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query, function (err, entries) { @@ -5364,7 +5363,7 @@ try { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }); @@ -5386,7 +5385,7 @@ Obtains all KV pairs that match the specified **Query** object for this device. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -5423,18 +5422,18 @@ try { } console.log(`entries: {entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query).then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) }); - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting Entries'); } catch (e) { console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); } @@ -5453,7 +5452,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------- | | deviceId | string | Yes | ID of the target device. | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| **Error codes** @@ -5489,7 +5488,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); var query = new distributedKVStore.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); @@ -5498,12 +5497,12 @@ try { console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); console.log(`entries.length: ${entries.length}`); console.log(`entries[0]: ${entries[0]}`); }) }); - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); } catch (e) { console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); } @@ -5522,7 +5521,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | -------------------- | | deviceId | string | Yes | ID of the target device.| -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | **Return value** @@ -5559,19 +5558,19 @@ try { } console.log(`entries: ${entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); var query = new distributedKVStore.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); kvStore.getEntries('localDeviceId', query).then((entries) => { - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); }).catch((err) => { console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); - console.log('Obtained the entries successfully.'); + console.log('Succeeded in getting entries'); } catch (e) { console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); } @@ -5624,20 +5623,20 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); kvStore.getResultSet('batch_test_string_key', async function (err, result) { if (err != undefined) { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }) }); }); @@ -5694,18 +5693,18 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -5750,14 +5749,14 @@ try { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully.'); + console.log('Succeeded in closing resultSet'); }) }); } catch (e) { @@ -5802,13 +5801,13 @@ let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully.'); + console.log('Succeeded in closing resultSet'); }).catch((err) => { console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); }); @@ -5830,7 +5829,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| **Error codes** @@ -5865,7 +5864,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query, async function (err, result) { @@ -5873,14 +5872,14 @@ try { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully.'); + console.log('Succeeded in closing resultSet'); }) }); }); @@ -5902,7 +5901,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | **Return value** @@ -5938,14 +5937,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); @@ -5953,7 +5952,7 @@ try { query.deviceId('localDeviceId'); console.log("GetResultSet " + query.getSqlLike()); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully.'); + console.log('Succeeded in closing resultSet'); }).catch((err) => { console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); }); @@ -5975,7 +5974,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -6011,14 +6010,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); @@ -6041,7 +6040,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | **Return value** @@ -6077,14 +6076,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('Obtained the result set successfully.'); + console.log('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); @@ -6092,7 +6091,7 @@ try { query.deviceId('localDeviceId'); console.log("GetResultSet " + query.getSqlLike()); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully.'); + console.log('Succeeded in closing resultSet'); }).catch((err) => { console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); }); @@ -6143,14 +6142,14 @@ try { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }) }); } catch (e) { @@ -6200,13 +6199,13 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates).then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -6257,14 +6256,14 @@ try { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }) }); } catch (e) { @@ -6314,13 +6313,13 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet('localDeviceId', predicates).then((result) => { - console.log('Obtained the result set successfully'); + console.log('Succeeded in getting result set'); resultSet = result; }).catch((err) => { console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Closed the result set successfully'); + console.log('Succeeded in closing result set'); }).catch((err) => { console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); }); @@ -6341,7 +6340,7 @@ Obtains the number of results that match the specified **Query** object for this | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------- | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results that match the specified **Query** object.| **Error codes** @@ -6371,7 +6370,7 @@ try { entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query, async function (err, resultSize) { @@ -6379,7 +6378,7 @@ try { console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained the result set size successfully'); + console.log('Succeeded in getting result set size'); }); }); } catch (e) { @@ -6399,7 +6398,7 @@ Obtains the number of results that match the specified **Query** object for this | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | Yes | **Query** object to match.| +| query | [Query](#query) | Yes | **Query** object to match.| **Return value** @@ -6434,14 +6433,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { - console.log('Obtained the result set size successfully'); + console.log('Succeeded in getting result set size'); }).catch((err) => { console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); }); @@ -6463,7 +6462,7 @@ Obtains the number of results that matches the specified device ID and **Query** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------------------- | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| **Error codes** @@ -6497,7 +6496,7 @@ try { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { @@ -6505,7 +6504,7 @@ try { console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); return; } - console.log('Obtained resultSize successfully'); + console.log('Succeeded in getting resultSize'); ; }); }); @@ -6527,7 +6526,7 @@ Obtains the number of results that matches the specified device ID and **Query** | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| -| query | [Query](query) | Yes | **Query** object to match. | +| query | [Query](#query) | Yes | **Query** object to match. | **Return value** @@ -6562,14 +6561,14 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Batch put data successfully.'); + console.log('Succeeded in putting batch'); }).catch((err) => { console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); }); var query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('Obtained resultSize successfully'); + console.log('Succeeded in getting resultSize'); ; }).catch((err) => { console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index 770689ba93a6a375f7d48a46d49cbe2334bd9bc3..506b940eae2f206b9a1bb5a10a39350abcd99753 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -368,8 +368,8 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | ----- | -| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.| -| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| +| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.| +| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** @@ -426,8 +426,8 @@ Continues a mission on a remote device. This API uses a promise to return the re | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | ----- | -| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.| -| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| +| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.| +| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.| **Return value** @@ -514,30 +514,3 @@ Defines the parameters required for registering a listener. | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | | deviceId | string | Yes | Yes | Device ID.| - -## ContinueDeviceInfo - -Defines the parameters required for mission continuation. - -**Required permissions**: ohos.permission.MANAGE_MISSIONS - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------- | -| srcDeviceId | string | Yes | Yes | ID of the source device.| -| dstDeviceId | string | Yes | Yes | ID of the target device.| -| missionId | number | Yes | Yes | Mission ID.| -| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.| - -## ContinueCallback - -Defines the callback invoked when the mission continuation is complete. - -**Required permissions**: ohos.permission.MANAGE_MISSIONS - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name | Type | Readable | Writable | Description | -| --------------------- | -------- | ---- | ---- | ------------------ | -| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. | diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 95b8eb45f0dc91295274ba2ff26087d3268dbce4..9c5499f62e4abf1bbeb14d53f823adc356103641 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -161,4 +161,4 @@ Describes the data passed in the event. | Name| Type | Readable| Writable| Description | | ---- | ------------------ | ---- | ---- | -------------- | -| data | [key: string]: any | Yes | Yes | Data carried by the event. The data type can be String, Integer, or Boolean.| +| data | [key: string]: any | Yes | Yes | Data carried by the event. The value can be a string, integer, or Boolean, wherein a string contains a maximum of 10240 bytes. | diff --git a/en/application-dev/reference/apis/js-apis-enterprise-accountManager.md b/en/application-dev/reference/apis/js-apis-enterprise-accountManager.md new file mode 100644 index 0000000000000000000000000000000000000000..6910779cd902d3368ad743ef1f6e4e179f2caf19 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-enterprise-accountManager.md @@ -0,0 +1,104 @@ +# @ohos.enterprise.accountManager (Account Management) + +The **accountManager** module provides account management capabilities for enterprise devices. Only the enterprise device administrator applications can call the APIs provided by this module. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import accountManager from '@ohos.enterprise.accountManager'; +``` + +## accountManager.disallowAddLocalAccount + +disallowAddLocalAccount(admin: Want, disallow: boolean, callback: AsyncCallback<void>): void + +Disallows local accounts. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| disallow | boolean | Yes | Whether to disallow local accounts. The value **true** means disallow local accounts; the value **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +accountManager.disallowAddLocalAccount(admin, true, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## accountManager.disallowAddLocalAccount + +disallowAddLocalAccount(admin: Want, disallow: boolean): Promise<void> + +Disallows local accounts. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| disallow | boolean | Yes | Whether to disallow local accounts. The value **true** means disallow local accounts; the value **false** means the opposite. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +accountManager.disallowAddLocalAccount(wantTemp, true).then(() => { + console.log("success"); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-enterprise-networkManager.md b/en/application-dev/reference/apis/js-apis-enterprise-networkManager.md new file mode 100644 index 0000000000000000000000000000000000000000..8e527defb2e34a3269b08f19c6bbd049569cff2e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-enterprise-networkManager.md @@ -0,0 +1,290 @@ +# @ohos.enterprise.networkManager (Network Management) + +The **networkManager** module provides network management capabilities for enterprise devices, including obtaining the device IP address and MAC address. Only the enterprise device administrator applications can call the APIs provided by this module. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import networkManager from '@ohos.enterprise.networkManager'; +``` + +## networkManager.getAllNetworkInterfaces + +getAllNetworkInterfaces(admin: Want, callback: AsyncCallback<Array<string>>): void + +Obtains all active network interfaces. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the active network interfaces obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getAllNetworkInterfaces(admin, (error, result) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + console.log(JSON.stringify(result)); +}); +``` + +## networkManager.getAllNetworkInterfaces + +getAllNetworkInterfaces(admin: Want): Promise<Array<string>> + +Obtains all active network interfaces. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<Array<string>> | Promise used to return the active network interfaces obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getAllNetworkInterfaces(wantTemp).then((result) => { + console.log(JSON.stringify(result)); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` + +## networkManager.getIpAddress + +getIpAddress(admin: Want, networkInterface: string, callback: AsyncCallback<string>): void + +Obtains the IP address of a device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| networkInterface | string | Yes | Network interface. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the device IP address obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getIpAddress(wantTemp, "eth0", (error, result) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + console.log(result); +}); +``` + +## networkManager.getIpAddress + +getIpAddress(admin: Want, networkInterface: string): Promise<string> + +Obtains the IP address of a device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| networkInterface | string | Yes | Network interface. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the device IP address obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getIpAddress(wantTemp, "eth0").then((result) => { + console.log(result); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` + +## networkManager.getMac + +getMac(admin: Want, networkInterface: string, callback: AsyncCallback<string>): void + +Obtains the MAC address of a device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| networkInterface | string | Yes | Network interface. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the device MAC address obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getMac(wantTemp, "eth0", (error, result) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + console.log(result); +}); +``` + +## networkManager.getMac + +getIpAddress(admin: Want, networkInterface: string): Promise<string> + +Obtains the MAC address of a device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| networkInterface | string | Yes | Network interface. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the device MAC address obtained. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +networkManager.getMac(wantTemp, "eth0").then((result) => { + console.log(result); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-enterprise-wifiManager.md b/en/application-dev/reference/apis/js-apis-enterprise-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..44ed633f182665681e3dbb844c38406113bf9ff7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @@ -0,0 +1,104 @@ +# @ohos.enterprise.wifiManager (Wi-Fi Management) + +The **wifiManager** module provides Wi-Fi management capabilities for enterprise devices. Only the enterprise device administrator applications can call the APIs provided by this module. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import wifiManager from '@ohos.enterprise.wifiManager'; +``` + +## wifiManager.isWifiActive + +isWifiActive(admin: Want, callback: AsyncCallback<boolean>): void + +Checks whether Wi-Fi is enabled. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return whether Wi-Fi is enabled. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +wifiManager.isWifiActive(wantTemp, (error, result) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + console.log(result); +}); +``` + +## wifiManager.isWifiActive + +isWifiActive(admin: Want): Promise<boolean> + +Checks whether Wi-Fi is active. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<boolean> | Promise used to return whether Wi-Fi is active. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | The application is not an administrator application of the device. | +| 9200002 | The administrator application does not have permission to manage the device.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +wifiManager.isWifiActive(wantTemp).then((result) => { + console.log(result); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index dba3fb3f36ce7a0043738ff1c7bce26f22ae4973..98ddcfd6e20d64d4ef664fec43637b29e207bca5 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -40,11 +40,9 @@ Defines the data structure of the fault log information. | summary | string | Yes| Summary of the fault.| | fullLog | string | Yes| Full log text.| -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +## faultLogger.query9+ -> **NOTE**
This API is deprecated since API version 9. You are advised to use [faultLogger.query](#faultloggerquery9) instead. +query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void Obtains the fault information about the current process. This API uses an asynchronous callback to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. @@ -57,6 +55,14 @@ Obtains the fault information about the current process. This API uses an asynch | faultType | [FaultType](#faulttype) | Yes| Fault type.| | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. +**Error codes** + +For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). + +| ID| Error Message| +| --- | --- | +| 10600001 | The service is not started or is faulty | + **Example** ```js @@ -79,14 +85,16 @@ function queryFaultLogCallback(error, value) { } } } -faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +try { + faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +} catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} ``` -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> +## faultLogger.query9+ -> **NOTE**
This API is deprecated since API version 9. You are advised to use [faultLogger.query](#faultloggerquery9-1) instead. +query(faultType: FaultType) : Promise<Array<FaultLogInfo>> Obtains the fault information about the current process. This API uses a promise to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. @@ -104,32 +112,48 @@ Obtains the fault information about the current process. This API uses a promise | -------- | -------- | | Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise used to return the fault information array. You can obtain the fault information instance in its **then()** method or use **await**.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval.| +**Error codes** + +For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). + +| ID| Error Message| +| --- | --- | +| 10600001 | The service is not started or is faulty | + **Example** ```js 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); + 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}`); } } ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [faultLogger.query](#faultloggerquery9) instead. Obtains the fault information about the current process. This API uses an asynchronous callback to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. @@ -142,14 +166,6 @@ Obtains the fault information about the current process. This API uses an asynch | faultType | [FaultType](#faulttype) | Yes| Fault type.| | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. -**Error codes** - -For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). - -| ID| Error Message| -| --- | --- | -| 10600001 | The service is not running or broken | - **Example** ```js @@ -172,16 +188,16 @@ function queryFaultLogCallback(error, value) { } } } -try { - faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); -} catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); -} +faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType) : Promise<Array<FaultLogInfo>> +querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [faultLogger.query](#faultloggerquery9-1) instead. Obtains the fault information about the current process. This API uses a promise to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. @@ -199,37 +215,25 @@ Obtains the fault information about the current process. This API uses a promise | -------- | -------- | | Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise used to return the fault information array. You can obtain the fault information instance in its **then()** method or use **await**.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval.| -**Error codes** - -For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). - -| ID| Error Message| -| --- | --- | -| 10600001 | The service is not running or broken | - **Example** ```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); - } + 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); } - } catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-file-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md index 9c340eef3974ed2875f417c71cb8a5f7dd4b10d8..c87c8465d7909f495baf6babad02e8e5b118424c 100644 --- a/en/application-dev/reference/apis/js-apis-file-environment.md +++ b/en/application-dev/reference/apis/js-apis-file-environment.md @@ -4,7 +4,7 @@ The **Environment** module provides APIs for obtaining the root directories of t > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs and cannot be called by third-party applications. > - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). @@ -26,7 +26,7 @@ Obtains the root directory of the storage. This API uses a promise to return the | Type | Description | | --------------------- | ---------------- | -| Promise<string> | Promise returned with the root directory of the storage.| +| Promise<string> | Promise used to return the root directory of the storage.| **Example** @@ -50,7 +50,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of the storage.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback invoked to return the root directory of the storage.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index 19ab5a4812762f0c812a843ad0db452801497dbe..306d752c6de0ec32a36b5bc024d8b88b016bcb3d 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -1666,7 +1666,7 @@ Lists all files in a directory. This API uses an asynchronous callback to return }); ``` -## listFileSync +## fs.listFileSync listFileSync(path: string, options?: { recursion?: boolean; @@ -1716,7 +1716,7 @@ Lists all files in a directory synchronously. This API supports recursive listin console.info("filename: %s", filenames[i]); } ``` -## moveFile +## fs.moveFile moveFile(src: string, dest: string, mode?: number): Promise; @@ -1742,7 +1742,7 @@ Moves a file. This API uses a promise to return the result. }); ``` -## moveFile +## fs.moveFile moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback): void; @@ -1771,7 +1771,7 @@ Moves a file. This API uses an asynchronous callback to return the result. }); ``` -## moveFileSync +## fs.moveFileSync moveFile(src: string, dest: string, mode?: number): void; @@ -2065,6 +2065,78 @@ Synchronously opens a stream based on the file descriptor. fs.closeSync(file); ``` +## fs.createWatcher10+ + +createWatcher(path: string, events: number, listener: WatchEventListener): Watcher + +Creates a **Watcher** object to observe file or directory changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| path | string | Yes | Path of the file or directory to observe in the application sandbox. | +| events | number | Yes | Events to observe. Multiple events can be separated|by a bitwise OR operator (|).
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted form the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **0xfff: IN_ALL_EVENTS**: All events.| +| listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | + +**Return value** + +| Type | Description | +| ------------------ | --------- | +| [Watcher](#watcher10) | **Watcher** object created.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent) => { + if (watchEvent.event == 0x2) { + console.info(watchEvent.fileName + 'was modified'); + } else if (watchEvent.event == 0x10) { + console.info(watchEvent.fileName + 'was closed'); + } + }); + watcher.start(); + fs.writeSync(file.fd, 'test'); + fs.closeSync(file); + watcher.stop(); + ``` + +## WatchEventListener10+ + +(event: WatchEvent): void + +Called when an observed event occurs. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| event | WatchEvent | Yes | Event for the callback to invoke. | + +## WatchEvent10+ + +Defines the event to observe. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------- | +| fileName | string | Yes | No | Name of the file for which the event occurs.| +| event | number | Yes | No | Events to observe. For details, see **events** in [createWatcher](#fscreatewatcher10).| +| cookie | number | Yes | No | Cookie bound with the event. Currently, only the **IN_MOVED_FROM** and **IN_MOVED_TO** events are supported. The **IN_MOVED_FROM** and **IN_MOVED_TO** events of the same file have the same **cookie** value.| + ## Stat Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously. @@ -2686,6 +2758,48 @@ Unlocks this file synchronously. console.log("unlock file successful"); ``` +## Watcher10+ + +Provides APIs for file or directory listening. Before using the APIs of **Watcher** , call **createWatcher()** to create a **Watcher** object. + +### start10+ + +start(): void + +Starts file or directory listening. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let watcher = fs.createWatcher(filePath, 0xfff, () => {}); + watcher.start(); + watcher.stop(); + ``` + +### stop10+ + +stop(): void + +Stops file or directory listening. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let watcher = fs.createWatcher(filePath, 0xfff, () => {}); + watcher.start(); + watcher.stop(); + ``` + ## OpenMode Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file. diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md new file mode 100644 index 0000000000000000000000000000000000000000..44e38fa5f4ef0b9b6af861ceb2ceeb1a8d126906 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -0,0 +1,771 @@ +# @ohos.file.picker (Picker) + +> **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. + +**Picker** encapsulates system applications, such as **PhotoViewPicker**, **DocumentViewPicker**, and **AudioViewPicker**, and provides capabilities of selecting and saving images, videos, documents, and audio clips. The application can select the picker as required. + +## Modules to Import +```js +import picker from '@ohos.file.picker'; +``` + +## PhotoViewPicker + +Provides APIs for selecting and saving images and videos. Before using the APIs of **PhotoViewPicker**, you need to create a **PhotoViewPicker** instance. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Example** + +```ts +let photoPicker = new picker.PhotoViewPicker(); +``` + +### select + +select(option?: PhotoSelectOptions) : Promise<PhotoSelectResult> + +Selects one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSelectOptions** to specify the media type and the maximum number of files to select. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [PhotoSelectOptions](#photoselectoptions) | No | Options for selecting images or videos.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| Promise<[PhotoSelectResult](#photoselectresult)> | Promise used to return information about the images or videos selected.| + +**Example** + +```ts +async function example() { + try { + let PhotoSelectOptions = new picker.PhotoSelectOptions(); + PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; + PhotoSelectOptions.maxSelectNumber = 5; + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { + console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); + }).catch((err) => { + console.error('PhotoViewPicker.select failed with err: ' + err); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(option: PhotoSelectOptions, callback: AsyncCallback<PhotoSelectResult>) : void + +Selects one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSelectOptions** to specify the media type and the maximum number of files to select. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [PhotoSelectOptions](#photoselectoptions) | Yes | Options for selecting images or videos.| +| callback | AsyncCallback<[PhotoSelectResult](#photoselectresult)> | Yes | Callback invoked to return information about the images or videos selected.| + +**Example** + +```ts +async function example() { + try { + let PhotoSelectOptions = new picker.PhotoSelectOptions(); + PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; + PhotoSelectOptions.maxSelectNumber = 5; + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.select(PhotoSelectOptions, (err, PhotoSelectResult) => { + if (err) { + console.error('PhotoViewPicker.select failed with err: ' + err); + return; + } + console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(callback: AsyncCallback<PhotoSelectResult>) : void + +Selects one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<[PhotoSelectResult](#photoselectresult)> | Yes | Callback invoked to return information about the images or videos selected.| + +**Example** + +```ts +async function example() { + try { + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.select((err, PhotoSelectResult) => { + if (err) { + console.error('PhotoViewPicker.select failed with err: ' + err); + return; + } + console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(option?: PhotoSaveOptions) : Promise<Array<string>> + +Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [PhotoSaveOptions](#photosaveoptions) | No | Options for saving images or videos.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| Promise<Array<string>> | Promise used to return the URIs of the files saved.| + +**Example** + +```ts +async function example() { + try { + let PhotoSaveOptions = new picker.PhotoSaveOptions(); + PhotoSaveOptions.newFileNames = ['PhotoViewPicker01.jpg', 'PhotoViewPicker01.mp4']; + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult) => { + console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); + }).catch((err) => { + console.error('PhotoViewPicker.save failed with err: ' + err); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(option: PhotoSaveOptions, callback: AsyncCallback<Array<string>>) : void + +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [PhotoSaveOptions](#photosaveoptions) | Yes | Options for saving images or videos.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the files saved.| + +**Example** + +```ts +async function example() { + try { + let PhotoSaveOptions = new picker.PhotoSaveOptions(); + PhotoSaveOptions.newFileNames = ['PhotoViewPicker02.jpg','PhotoViewPicker02.mp4']; + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.save(PhotoSaveOptions, (err, PhotoSaveResult) => { + if (err) { + console.error('PhotoViewPicker.save failed with err: ' + err); + return; + } + console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(callback: AsyncCallback<Array<string>>) : void + +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the files saved.| + +**Example** + +```ts +async function example() { + try { + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.save((err, PhotoSaveResult) => { + if (err) { + console.error('PhotoViewPicker.save failed with err: ' + err); + return; + } + console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); + }); + } catch (err) { + console.error('PhotoViewPicker failed with err: ' + err); + } +} +``` + +## DocumentViewPicker + +Provides APIs for selecting and saving non-media files, for example, documents in a variety of formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Example** + +```ts +let documentPicker = new picker.DocumentViewPicker(); +``` + +### select + +select(option?: DocumentSelectOptions) : Promise<Array<string>> + +Selects one or more documents in a **documentPicker** page. This API uses a promise to return the result. You can pass in **DocumentSelectOptions**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [DocumentSelectOptions](#documentselectoptions) | No | Options for selecting documents.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| Promise<Array<string>> | Promise used to return the URIs of the documents selected.| + +**Example** + +```ts +async function example() { + try { + let DocumentSelectOptions = new picker.DocumentSelectOptions(); + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => { + console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); + }).catch((err) => { + console.error('DocumentViewPicker.select failed with err: ' + err); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(option: DocumentSelectOptions, callback: AsyncCallback<Array<string>>) : void + +Selects one or more documents in a **documentPicker** page. This API uses an asynchronous callback to return the result. You can pass in **DocumentSelectOptions**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [DocumentSelectOptions](#documentselectoptions) | Yes | Options for selecting documents.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the documents selected.| + +**Example** + +```ts +async function example() { + try { + let DocumentSelectOptions = new picker.DocumentSelectOptions(); + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.select(DocumentSelectOptions, (err, DocumentSelectResult) => { + if (err) { + console.error('DocumentViewPicker.select failed with err: ' + err); + return; + } + console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(callback: AsyncCallback<Array<string>>) : void + +Selects one or more documents in a **documentPicker** page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the documents selected.| + +**Example** + +```ts +async function example() { + try { + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.select((err, DocumentSelectResult) => { + if (err) { + console.error('DocumentViewPicker.select failed with err: ' + err); + return; + } + console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + + +### save + +save(option?: DocumentSaveOptions) : Promise<Array<string>> + +Saves one or more documents in a **documentPicker** page. This API uses a promise to return the result. You can pass in **DocumentSaveOptions** to specify the file names to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [DocumentSaveOptions](#documentsaveoptions) | No | Options for saving the documents.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| Promise<Array<string>> | Promise used to return the URIs of the documents saved.| + +**Example** + +```ts +async function example() { + try { + let DocumentSaveOptions = new picker.DocumentSaveOptions(); + DocumentSaveOptions.newFileNames = ['DocumentViewPicker01.txt']; + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult) => { + console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); + }).catch((err) => { + console.error('DocumentViewPicker.save failed with err: ' + err); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(option: DocumentSaveOptions, callback: AsyncCallback<Array<string>>) : void + +Saves one or more documents in a **documentPicker** page. This API uses an asynchronous callback to return the result. You can pass in **DocumentSaveOptions** to specify the file names to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [DocumentSaveOptions](#documentsaveoptions) | Yes | Options for saving the documents.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the documents saved.| + +**Example** + +```ts +async function example() { + try { + let DocumentSaveOptions = new picker.DocumentSaveOptions(); + DocumentSaveOptions.newFileNames = ['DocumentViewPicker02.txt']; + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.save(DocumentSaveOptions, (err, DocumentSaveResult) => { + if (err) { + console.error('DocumentViewPicker.save failed with err: ' + err); + return; + } + console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(callback: AsyncCallback<Array<string>>) : void + +Saves one or more documents in a **documentPicker** page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the documents saved.| + +**Example** + +```ts +async function example() { + try { + let documentPicker = new picker.DocumentViewPicker(); + documentPicker.save((err, DocumentSaveResult) => { + if (err) { + console.error('DocumentViewPicker.save failed with err: ' + err); + return; + } + console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); + }); + } catch (err) { + console.error('DocumentViewPicker failed with err: ' + err); + } +} +``` + +## AudioViewPicker + +Provides APIs for selecting and saving audio files. Before using the APIs of **AudioViewPicker**, you need to create an **AudioViewPicker** instance. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Example** + +```ts +let audioPicker = new picker.AudioViewPicker(); +``` + +### select + +select(option?: AudioSelectOptions) : Promise<Array<string>> + +Selects one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses a promise to return the result. You can pass in **AudioSelectOptions**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [AudioSelectOptions](#audioselectoptions) | No | Options for selecting audio files.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| Promise<Array<string>> | Promise used to return the URIs of the audio files selected.| + +**Example** + +```ts +async function example() { + try { + let AudioSelectOptions = new picker.AudioSelectOptions(); + let audioPicker = new picker.AudioViewPicker(); + audioPicker.select(AudioSelectOptions).then((AudioSelectResult) => { + console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); + }).catch((err) => { + console.error('AudioViewPicker.select failed with err: ' + err); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(option: AudioSelectOptions, callback: AsyncCallback<Array<string>>) : void + +Selects one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses an asynchronous callback to return the result. You can pass in **AudioSelectOptions**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [AudioSelectOptions](#audioselectoptions) | Yes | Options for selecting audio files.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the audio files selected.| + +**Example** + +```ts +async function example() { + try { + let AudioSelectOptions = new picker.AudioSelectOptions(); + let audioPicker = new picker.AudioViewPicker(); + audioPicker.select(AudioSelectOptions, (err, AudioSelectResult) => { + if (err) { + console.error('AudioViewPicker.select failed with err: ' + err); + return; + } + console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +### select + +select(callback: AsyncCallback<Array<string>>) : void + +Selects one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the audio files selected.| + +**Example** + +```ts +async function example() { + try { + let audioPicker = new picker.AudioViewPicker(); + audioPicker.select((err, AudioSelectResult) => { + if (err) { + console.error('AudioViewPicker.select failed with err: ' + err); + return; + } + console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(option?: AudioSaveOptions) : Promise<Array<string>> + +Saves one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses a promise to return the result. You can pass in **AudioSaveOptions** to specify the file names of the audio clips to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [AudioSaveOptions](#audiosaveoptions) | No | Options for saving audio files.| + +**Return value** + +| Type | Description | +| ----------------------------- | ---- | +| Promise<Array<string>> | Promise used to return the URIs of the audio files saved.| + +**Example** + +```ts +async function example() { + try { + let AudioSaveOptions = new picker.AudioSaveOptions(); + AudioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; + let audioPicker = new picker.AudioViewPicker(); + audioPicker.save(AudioSaveOptions).then((AudioSaveResult) => { + console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)) + }).catch((err) => { + console.error('AudioViewPicker.save failed with err: ' + err); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(option: AudioSaveOptions, callback: AsyncCallback<Array<string>>) : void + +Saves one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses an asynchronous callback to return the result. You can pass in **AudioSaveOptions** to specify the file names of the audio clips to save. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| option | [AudioSaveOptions](#audiosaveoptions) | Yes | Options for saving audio files.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the audio files saved.| + +**Example** + +```ts +async function example() { + try { + let AudioSaveOptions = new picker.AudioSaveOptions(); + AudioSaveOptions.newFileNames = ['AudioViewPicker02.mp3']; + let audioPicker = new picker.AudioViewPicker(); + audioPicker.save(AudioSaveOptions, (err, AudioSaveResult) => { + if (err) { + console.error('AudioViewPicker.save failed with err: ' + err); + return; + } + console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +### save + +save(callback: AsyncCallback<Array<string>>) : void + +Saves one or more audio files in an **audioPicker** page (currently, a **documentPicker** page is displayed). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the URIs of the audio files saved.| + +**Example** + +```ts +async function example() { + try { + let audioPicker = new picker.AudioViewPicker(); + audioPicker.save((err, AudioSaveResult) => { + if (err) { + console.error('AudioViewPicker.save failed with err: ' + err); + return; + } + console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); + }); + } catch (err) { + console.error('AudioViewPicker failed with err: ' + err); + } +} +``` + +## PhotoViewMIMETypes + +Enumerates the media file types that can be selected. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Value| Description| +| ----- | ---- | ---- | +| IMAGE_TYPE | 'image/*' | Image.| +| VIDEO_TYPE | 'video/*' | Video.| +| IMAGE_VIDEO_TYPE | '\*/*' | Image and video.| + +## PhotoSelectOptions + +Defines the options for selecting images or videos. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | -------------------------------- | +| MIMEType? | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Media file types to select.| +| maxSelectNumber? | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | + +## PhotoSelectResult + +Defines information about the images or videos selected. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ------------------- | ---- | ---- | ------------------------------ | +| photoUris | Array<string> | Yes | Yes | URIs of the media files selected.| +| isOriginalPhoto | boolean | Yes | Yes | Whether the selected media file is the original image.| + +## PhotoSaveOptions + +Defines the options for saving images or videos. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---------------------------- | +| newFileNames? | Array<string> | No | Files names of the images or videos to save.| + +## DocumentSelectOptions + +Defines the options for selecting documents. Currently, this parameter cannot be configured. + +**System capability**: SystemCapability.FileManagement.UserFileService + +## DocumentSaveOptions + +Defines the options for saving documents. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---------------------------- | +| newFileNames? | Array<string> | No | File names of the documents to save.| + +## AudioSelectOptions + +Defines the options for selecting audio clips. Currently, this parameter cannot be configured. + +**System capability**: SystemCapability.FileManagement.UserFileService + +## AudioSaveOptions + +Defines the options for saving audio files. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---------------------------- | +| newFileNames? | Array<string> | No | File names of the audio clips to save.| diff --git a/en/application-dev/reference/apis/js-apis-file-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md index b9071ecc64025491ed21e55490f4753b83440eb1..c564516e66c0119dbec070c4a9eab744350d130f 100644 --- a/en/application-dev/reference/apis/js-apis-file-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -5,7 +5,7 @@ The **securityLabel** module provides APIs for managing data security levels of > **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 support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -45,7 +45,7 @@ For details about how to obtain the FA model context, see [Context](js-apis-inne ## securityLabel.setSecurityLabel -setSecurityLabel(path:string, type:dataLevel):Promise<void> +setSecurityLabel(path:string, type:DataLevel):Promise<void> Sets a security label for a file in asynchronous mode. This API uses a promise to return the result. @@ -56,7 +56,7 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t | Name | Type | Mandatory| Description | | --------- | ------ | ---- | -------------------------------------------- | | path | string | Yes | Path of the target file. | -| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| **Return value** @@ -67,7 +67,8 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t **Example** ```js - securityLabel.setSecurityLabel(path, "s0").then(() => { + let filePath = pathDir + '/test.txt'; + securityLabel.setSecurityLabel(filePath, "s0").then(() => { console.info("setSecurityLabel successfully"); }).catch((err) => { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); @@ -76,7 +77,7 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t ## securityLabel.setSecurityLabel -setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void +setSecurityLabel(path:string, type:DataLevel, callback: AsyncCallback<void>):void Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result. @@ -87,13 +88,14 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | -------------------------------------------- | | path | string | Yes | Path of the target file. | -| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** ```js - securityLabel.setSecurityLabel(path, "s0", (err) => { + let filePath = pathDir + '/test.txt'; + securityLabel.setSecurityLabel(filePath, "s0", (err) => { if (err) { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -104,7 +106,7 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro ## securityLabel.setSecurityLabelSync -setSecurityLabelSync(path:string, type:dataLevel):void +setSecurityLabelSync(path:string, type:DataLevel):void Sets a security label for a file in synchronous mode. @@ -115,12 +117,13 @@ Sets a security label for a file in synchronous mode. | Name | Type | Mandatory| Description | | --------- | ------ | ---- | -------------------------------------------- | | path | string | Yes | Path of the target file. | -| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| **Example** ```js -securityLabel.setSecurityLabelSync(path, "s0"); +let filePath = pathDir + '/test.txt'; +securityLabel.setSecurityLabelSync(filePath, "s0"); ``` ## securityLabel.getSecurityLabel @@ -146,7 +149,8 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi **Example** ```js - securityLabel.getSecurityLabel(path).then((type) => { + let filePath = pathDir + '/test.txt'; + securityLabel.getSecurityLabel(filePath).then((type) => { console.log("getSecurityLabel successfully, Label: " + type); }).catch((err) => { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); @@ -171,7 +175,8 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb **Example** ```js - securityLabel.getSecurityLabel(path, (err, type) => { + let filePath = pathDir + '/test.txt'; + securityLabel.getSecurityLabel(filePath, (err, type) => { if (err) { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -202,6 +207,7 @@ Obtains the security label of a file in synchronous mode. **Example** ```js -let type = securityLabel.getSecurityLabelSync(path); +let filePath = pathDir + '/test.txt'; +let type = securityLabel.getSecurityLabelSync(filePath); console.log("getSecurityLabel successfully, Label: " + type); ``` diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md index 6238db4bd28dd10cb7ac75014778827eda399f4f..41c76565f967a2ea057f9c81ca3328a1cc047a07 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,11 +1,12 @@ # @ohos.file.fileAccess (User File Access and Management) -The **fileAccess** module is a framework for accessing and operating user files based on the Extension ability mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. +The **fileAccess** module is a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. >**NOTE** > >- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **Files**. +>- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **picker** and **fs**. +>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -25,9 +26,9 @@ Obtains information about all wants with **extension** set to **fileAccess** in **Return value** - | Type| Description| - | --- | -- | - | Promise<Array<Want>> | Promise used to return the **want** information obtained.| +| Type| Description| +| --- | -- | +| Promise<Array<Want>> | Promise used to return the **want** information obtained.| **Example** @@ -55,9 +56,9 @@ Obtains information about all wants with **extension** set to **fileAccess** in **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.| **Example** @@ -89,23 +90,23 @@ Synchronously creates a **Helper** object to connect to the specified wants. The **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | context | Context | Yes| Context of the ability.| - | wants | Array<Want> | Yes| Wants to connect.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| context | Context | Yes| Context of the ability.| +| wants | Array<Want> | Yes| Wants to connect.| **Return value** - | Type| Description| - | --- | -- | - | FileAccessHelper | **Helper** object created.| +| Type| Description| +| --- | -- | +| FileAccessHelper | **Helper** object created.| **Example** ```js createFileAccessHelper() { let fileAccessHelper = null; - / / Obtain wantInfos by using getFileAccessAbilityInfo(). + // Obtain wantInfos by using getFileAccessAbilityInfo(). // Create a helper object to interact with the media library service only. let wantInfos = [ { @@ -136,15 +137,15 @@ Synchronously creates a **Helper** object to connect to all file management serv **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | context | Context | Yes| Context of the ability.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| context | Context | Yes| Context of the ability.| **Return value** - | Type| Description| - | --- | -- | - | FileAccessHelper | **Helper** object created.| +| Type| Description| +| --- | -- | +| FileAccessHelper | **Helper** object created.| **Example** @@ -175,9 +176,9 @@ Obtains information about the device root nodes of the file management service t **Return value** - | Type| Description| - | --- | -- | - | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| +| Type| Description| +| --- | -- | +| Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| **Example** @@ -219,9 +220,9 @@ The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.| **Example** @@ -262,16 +263,16 @@ Synchronously obtains the **FileIterator** object of the first-level files (dire **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | -- | -- | - | filter | Filter | No| **Filter** object. | +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | **Return value** - | Type| Description| - | --- | -- | - | FileIterator | **FileIterator** object obtained.| +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| **Example** @@ -313,15 +314,15 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | -- | -- | - | filter | Filter | No| **Filter** object. | +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | **Return value** - | Type| Description| - | --- | -- | - | FileIterator | **FileIterator** object obtained.| +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| **Example** @@ -363,15 +364,15 @@ Synchronously obtains the **FileIterator** object of the next-level files (direc **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | -- | -- | - | filter | Filter | No| **Filter** object. | +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | **Return value** - | Type| Description| - | --- | -- | - | FileIterator | **FileIterator** object obtained.| +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| **Example** @@ -413,16 +414,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | -- | -- | - | filter | Filter | No| **Filter** object. | +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | **Return value** - | Type| Description| - | --- | -- | - | FileIterator | **FileIterator** object obtained.| +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| **Example** @@ -464,10 +465,10 @@ Creates a file in a directory. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the parent directory for the file to create.| - | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the parent directory for the file to create.| +| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| **Return value** @@ -509,11 +510,11 @@ Creates a file in a directory. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the parent directory for the file to create.| - | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| - | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the parent directory for the file to create.| +| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| +| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.| **Example** @@ -541,7 +542,7 @@ Creates a file in a directory. This API uses an asynchronous callback to return mkDir(parentUri: string, displayName: string) : Promise<string> -Creates a directory in a directory. This API uses a promise to return the result. +Creates a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -549,10 +550,10 @@ Creates a directory in a directory. This API uses a promise to return the result **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | parentUri | string | Yes| URI of the parent directory for the directory to create.| - | displayName | string | Yes| Name of the directory to create.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| parentUri | string | Yes| URI of the parent directory for the directory to create.| +| displayName | string | Yes| Name of the directory to create.| **Return value** @@ -586,7 +587,7 @@ Creates a directory in a directory. This API uses a promise to return the result mkDir(parentUri: string, displayName: string, callback: AsyncCallback<string>) : void; -Creates a directory in a directory. This API uses an asynchronous callback to return the result. +Creates a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -594,11 +595,11 @@ Creates a directory in a directory. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | parentUri | string | Yes| URI of the parent directory for the directory to create.| - | displayName | string | Yes| Name of the directory to create.| - | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the directory created.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| parentUri | string | Yes| URI of the parent directory for the directory to create.| +| displayName | string | Yes| Name of the directory to create.| +| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the directory created.| **Example** @@ -634,10 +635,10 @@ Opens a file. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file to open.| - | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file to open.| +| flags | [OPENFLAGS](#openflags) | Yes| File open mode.| **Return value** @@ -672,11 +673,11 @@ Opens a file. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file to open.| - | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the file descriptor of the file opened.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file to open.| +| flags | [OPENFLAGS](#openflags) | Yes| File open mode.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the file descriptor of the file opened.| **Example** @@ -711,9 +712,9 @@ Deletes a file or directory. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file or directory to delete.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or directory to delete.| **Return value** @@ -750,10 +751,10 @@ Deletes a file or directory. This API uses an asynchronous callback to return th **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file or directory to delete.| - | callback | AsyncCallback<number> | Yes| Promise used to return the result.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or directory to delete.| +| callback | AsyncCallback<number> | Yes| Promise used to return the result.| **Example** @@ -788,10 +789,10 @@ Moves a file or directory. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | sourceFile | string | Yes| URI of the file or directory to move.| - | destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFile | string | Yes| URI of the file or directory to move.| +| destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| **Return value** @@ -828,11 +829,11 @@ Moves a file or directory. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | sourceFile | string | Yes| URI of the file or directory to move.| - | destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| - | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or directory in the destination directory.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFile | string | Yes| URI of the file or directory to move.| +| destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| +| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or directory in the destination directory.| **Example** @@ -868,10 +869,10 @@ Renames a file or directory. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file or directory to rename.| - | displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or directory to rename.| +| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| **Return value** @@ -907,11 +908,11 @@ Renames a file or directory. This API uses an asynchronous callback to return th **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | uri | string | Yes| URI of the file or directory to rename.| - | displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| - | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or directory.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or directory to rename.| +| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| +| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or directory.| **Example** @@ -946,9 +947,9 @@ Checks whether a file or directory exists. This API uses a promise to return the **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | sourceFileUri | string | Yes| URI of the file or directory.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFileUri | string | Yes| URI of the file or directory.| **Return value** @@ -987,10 +988,10 @@ Checks whether a file or directory exists. This API uses an asynchronous callbac **Parameters** - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | sourceFileUri | string | Yes| URI of the file or directory.| - | callback | AsyncCallback<boolean> | Yes| Promise used to return the result.| +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFileUri | string | Yes| URI of the file or directory.| +| callback | AsyncCallback<boolean> | Yes| Promise used to return the result.| **Example** @@ -1016,6 +1017,241 @@ Checks whether a file or directory exists. This API uses an asynchronous callbac }; ``` +## FileAccessHelper.getFileInfoFromUri10+ + +getFileInfoFromUri(uri: string) : Promise; + +Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or directory.| + +**Return value** + +| Type| Description| +| --- | -- | +| [FileInfo](#fileinfo) | Promise used to return the **FileInfo** object obtained.| + +**Example** + + ```js + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri); + } catch (error) { + console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getFileInfoFromUri10+ + +getFileInfoFromUri(uri: string, callback: AsyncCallback) : void; + +Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of a file or directory.| +| callback | AsyncCallback<string> | Yes| Callback invoked to return the **FileInfo** object obtained.| + +**Example** + + ```js + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.getFileInfoFromUri(sourceUri, function (err, fileInfo) { + if (err) { + console.error("Failed to getFileInfoFromUri in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("getFileInfoFromUri success, fileInfo: " + JSON.stringify(fileInfo)); + }); + } catch (error) { + console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + + +## FileAccessHelper.getFileInfoFromRelativePath10+ + +getFileInfoFromRelativePath(relativePath: string) : Promise; + +Obtains a [FileInfo](#fileinfo) object based on the specified relative path. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| relativePath | string | Yes| Relative path of a file or directory.| + +**Return value** + +| Type| Description| +| --- | -- | +| [FileInfo](#fileinfo) | Promise used to return the **FileInfo** object obtained.| + +**Example** + + ```js + // The relative path of the media library is used as an example. + // In the sample code, relativePath indicates the download directory, which is the relativePath in fileInfo. + // You can use the relativePath obtained. + let relativePath = "Download/"; + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(relativePath); + } catch (error) { + console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getFileInfoFromRelativePath10+ + +getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback) : void; + +Obtains a [FileInfo](#fileinfo) object based on the specified relative path. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| relativePath | string | Yes| Relative path of a file or directory.| +| callback | AsyncCallback<string> | Yes| Callback invoked to return the **FileInfo** object obtained.| + +**Example** + + ```js + // The relative path of the media library is used as an example. + // In the sample code, relativePath indicates the download directory, which is the relativePath in fileInfo. + // You can use the relativePath obtained. + let relativePath = "Download/"; + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.getFileInfoFromRelativePath(relativePath, function (err, fileInfo) { + if (err) { + console.error("Failed to getFileInfoFromRelativePath in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("getFileInfoFromRelativePath success, fileInfo: " + JSON.stringify(fileInfo)); + }); + } catch (error) { + console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getThumbnail10+ + +getThumbnail(uri: string, size: image.Size) : Promise<image.PixelMap> + +Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ----------- | +| uri | string | Yes | URI of the media file.| +| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail. | + +**Return value** + +| Type | Description | +| :---------------------------- | :----------------- | +| Promise<image.PixelMap> | Promise used to return the **Pixelmap** object obtained.| + +**Example** + +```js +// The media library URI is used as an example. +// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo. +// You can use the URI obtained. +let targetUri = "datashare:///media/image/100"; +let size = { width: 128, height: 128 }; +try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let pixelMap = await fileAccessHelper.getThumbnail(targetUri, size); + let imageInfo = await pixelMap.getImageInfo(); + console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); + console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); +} catch (error) { + console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); +}; +``` + +## FileAccessHelper.getThumbnail10+ + + getThumbnail(uri: string, size: image.Size, callback: AsyncCallback<image.PixelMap>) : void + +Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------ | +| uri | string | Yes | URI of the media file. | +| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail. | +| callback | AsyncCallback<image.PixelMap> | Yes | Callback invoked to return the **Pixelmap** object obtained.| + +**Example** + +```js +// The media library URI is used as an example. +// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo. +// You can use the URI obtained. +let targetUri = "datashare:///media/image/100"; +let size = { width: 128, height: 128 }; +try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.getThumbnail(targetUri, size, async(err, pixelMap) => { + if (err) { + console.error("Failed to getThumbnail in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + let imageInfo = await pixelMap.getImageInfo(); + console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); + console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); + }); +} catch (error) { + console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); +}; +``` + ## RootIterator.next next( ) : { value: RootInfo, done: boolean } @@ -1062,6 +1298,7 @@ Represents the root attribute information and interface capabilities of a device | ------ | ------ | -------- | ------ | -------- | | deviceType | number | Yes| No|Device type.| | uri | string | Yes| No| Root directory URI of the device.| +| relativePath10+ | string | Yes| No| Relative path of the root directory.| | displayName | string | Yes| No| Device name.| | deviceFlags | number | Yes| No| Capabilities supported by the device.| @@ -1078,6 +1315,7 @@ Represents the file or directory attribute information and interface capabilitie | Name| Type | Readable| Writable| Description | | ------ | ------ | -------- | ------ | -------- | | uri | string | Yes| No| URI of the file or directory.| +| relativePath10+ | string | Yes| No| Relative path of a file or directory.| | fileName | string | Yes| No| Name of a file or directory.| | mode | number | Yes| No| Permissions on the file or directory.| | size | number | Yes| No| Size of the file or directory.| diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md index f9d6d9087b803775363799700cedc2f8dc31a2d1..0d56943e531718578ac4d0238bb2f6770df277d7 100644 --- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -782,12 +782,12 @@ For details about the following error codes, see [Location Error Codes](../error { bundleName: "com.example.myapplication", abilityName: "EntryAbility", - action: "action1", + action: "action1" } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -840,7 +840,7 @@ For details about the following error codes, see [Location Error Codes](../error { bundleName: "com.example.myapplication", abilityName: "EntryAbility", - action: "action1", + action: "action1" } ], operationType: wantAgent.OperationType.START_ABILITY, diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 3cd5b2408e9f527194bcd78eb8a4d9a1ea579907..3bf1e990cd2fcb0f2853c224d0adf70ce5e7b5dc 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -411,7 +411,7 @@ Registers a listener for status change events of the specified geofence. { bundleName: "com.example.myapplication", abilityName: "EntryAbility", - action: "action1", + action: "action1" } ], operationType: wantAgent.OperationType.START_ABILITY, diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 1a6339e406c98eb2dfd81239da3e852bcb4afe47..4d6d81f15430a456eb60f54e1b650df5ef112dbe 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -46,11 +46,11 @@ Adds one or more rules. HiChecker detects unexpected operations or gives feedbac ```js try { // Add a rule. - hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);} + hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // Add multiple rules. - hichecker.addCheckRule( - hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); -catch (err) { + // hichecker.addCheckRule( + // hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); +} catch (err) { console.error(`code: ${err.code}, message: ${err.message}`); } ``` @@ -76,9 +76,9 @@ try { // Remove a rule. hichecker.removeCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // Remove multiple rules. - hichecker.removeCheckRule( - hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); -catch (err) { + // hichecker.removeCheckRule( + // hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); +} catch (err) { console.error(`code: ${err.code}, message: ${err.message}`); } ``` @@ -113,7 +113,7 @@ try { // Check whether the added rule exists in the collection of added rules. hichecker.containsCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; hichecker.containsCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // return false; -catch (err) { +} catch (err) { console.error(`code: ${err.code}, message: ${err.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 189d855e894451790976eee2c3816cf17ae950b9..364938ddfa2864850a1335cb886f41e3de2c1a9c 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -297,7 +297,7 @@ import hidebug from '@ohos.hidebug' try { hidebug.startJsCpuProfiling("cpu_profiling"); - ... + // ... hidebug.stopJsCpuProfiling(); } catch (error) { console.info(error.code) @@ -326,7 +326,7 @@ import hidebug from '@ohos.hidebug' try { hidebug.startJsCpuProfiling("cpu_profiling"); - ... + // ... hidebug.stopJsCpuProfiling(); } catch (error) { console.info(error.code) diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 86e09db17bda0e6efa68bbeeb973a26f4a4ff467..2960e201db397e160dfc5cca7e1c729beebcb6a4 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -1,8 +1,9 @@ # @ohos.hiviewdfx.hiAppEvent (Application Event Logging) -The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. +This module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. -> **NOTE**
+> **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. @@ -447,27 +448,27 @@ Enumerates event types. | BEHAVIOR | 4 | Behavior event.| -## Event +## event Provides constants that define the names of all predefined events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type | Readable| Writable| Description | -| ------------------------- | ------ | ---- | ---- | -------------------- | -| USER_LOGIN | string | Yes | No | User login event. | -| USER_LOGOUT | string | Yes | No | User logout event. | -| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| +| Name | Type | Description | +| ------------------------- | ------ | -------------------- | +| USER_LOGIN | string | User login event. | +| USER_LOGOUT | string | User logout event. | +| DISTRIBUTED_SERVICE_START | string | Distributed service startup event.| -## Param +## param Provides constants that define the names of all predefined event parameters. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type | Readable| Writable| Description | -| ------------------------------- | ------ | ---- | ---- | ------------------ | -| USER_ID | string | Yes | No | Custom user ID. | -| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| +| Name | Type | Description | +| ------------------------------- | ------ | ------------------ | +| USER_ID | string | Custom user ID. | +| DISTRIBUTED_SERVICE_NAME | string | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 3735792dd3f5ce66569fbebf3a1036019e7457ed..4335d191f899346a3f0644c8f3571a0eff7c8212 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -2,8 +2,10 @@ The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. -> **NOTE**
-> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>**NOTE** +> +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ## Modules to Import @@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca import http from '@ohos.net.http'; ``` -## Example +## Examples ```js +// Import the HTTP namespace. import http from '@ohos.net.http'; // Each httpRequest corresponds to an HTTP request task and cannot be reused. @@ -24,7 +27,7 @@ httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. + // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. "EXAMPLE_URL", { method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. @@ -42,16 +45,19 @@ httpRequest.request( connectTimeout: 60000 // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. + usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. }, (err, data) => { if (!err) { // data.result carries the HTTP response. Parse the response based on service requirements. - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); // data.header carries the HTTP response header. Parse the content based on service requirements. console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + data.cookies); // 8+ + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ } else { console.info('error:' + JSON.stringify(err)); + // Unsubscribe from HTTP Response Header events. + httpRequest.off('headersReceive'); // Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy(); } @@ -61,7 +67,7 @@ httpRequest.request( ## http.createHttp -createHttp\(\): HttpRequest +createHttp(): HttpRequest Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request. @@ -70,8 +76,8 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req **Return value** | Type | Description | -| ---------- | ----------------------------------------------------------- | -| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| +| :---------- | :----------------------------------------------------------- | +| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.| **Example** @@ -82,14 +88,17 @@ let httpRequest = http.createHttp(); ## HttpRequest -Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. +Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp()](#httpcreatehttp) to create an **HttpRequestTask** object. ### request -request\(url: string, callback: AsyncCallback\\):void +request(url: string, callback: AsyncCallback\):void Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. +>**NOTE** +>This API supports only transfer of data not greater than 5 MB. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -101,6 +110,22 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback | url | string | Yes | URL for initiating an HTTP request.| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300007 | Couldn't connect to server. | +| 2300028 | Timeout was reached. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). + **Example** ```js @@ -118,10 +143,13 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { ### request -request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void +request(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. +>**NOTE** +>This API supports only transfer of data not greater than 5 MB. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -134,6 +162,46 @@ Initiates an HTTP request containing specified options to a given URL. This API | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). + **Example** ```js @@ -161,9 +229,12 @@ httpRequest.request("EXAMPLE_URL", ### request -request\(url: string, options? : HttpRequestOptions\): Promise +request(url: string, options? : HttpRequestOptions): Promise\ -Initiates an HTTP request to a given URL. This API uses a promise to return the result. +Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. + +>**NOTE** +>This API supports only transfer of data not greater than 5 MB. **Required permissions**: ohos.permission.INTERNET @@ -179,9 +250,48 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Return value** | Type | Description | -| ------------------------------------- | -------------------------------- | +| :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). **Example** @@ -208,7 +318,7 @@ promise.then((data) => { ### destroy -destroy\(\): void +destroy(): void Destroys an HTTP request. @@ -220,14 +330,217 @@ Destroys an HTTP request. httpRequest.destroy(); ``` -### on\('headerReceive'\) +### request210+ + +request2(url: string, callback: AsyncCallback\): void + +Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300007 | Couldn't connect to server. | +| 2300028 | Timeout was reached. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). + +**Example** + +```js +httpRequest.request2("EXAMPLE_URL", (err) => { + if (!err) { + console.info("request2 OK!"); + } else { + console.info("request2 ERROR : err = " + JSON.stringify(err)); + } +}) +``` + +### request210+ + +request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void + +Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). + +**Example** + +```js +httpRequest.request2("EXAMPLE_URL", +{ + method: http.RequestMethod.GET, + header: { + 'Content-Type': 'application/json' + }, + readTimeout: 60000, + connectTimeout: 60000 +}, (err) => { + if (!err) { + console.info("request2 OK!"); + } else { + console.info("request2 ERROR : err = " + JSON.stringify(err)); + } +}) +``` +### request210+ + +request2(url: string, options? : HttpRequestOptions): Promise\ + +Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| + +**Return value** + +| Type | Description | +| :------------------------------------- | :-------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**NOTE** +> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). +> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see: + +**Example** + +```js +let promise = httpRequest.request("EXAMPLE_URL", { + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: { + 'Content-Type': 'application/json' + } +}); +promise.then(() => { + console.info("request2 OK!"); +}).catch((err) => { + console.info("request2 ERROR : err = " + JSON.stringify(err)); +}); +``` + +### on('headerReceive') -on\(type: 'headerReceive', callback: AsyncCallback\): void +on(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. >**NOTE** ->This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. +>This API has been deprecated. You are advised to use [on('headersReceive')8+](#onheadersreceive8) instead. **System capability**: SystemCapability.Communication.NetStack @@ -241,24 +554,20 @@ Registers an observer for HTTP Response Header events. **Example** ```js -httpRequest.on('headerReceive', (err, data) => { - if (!err) { - console.info('header: ' + JSON.stringify(data)); - } else { - console.info('error:' + JSON.stringify(err)); - } +httpRequest.on('headerReceive', (data) => { + console.info('error:' + JSON.stringify(data)); }); ``` -### off\('headerReceive'\) +### off('headerReceive') -off\(type: 'headerReceive', callback?: AsyncCallback\): void +off(type: 'headerReceive', callback?: AsyncCallback\): void Unregisters the observer for HTTP Response Header events. >**NOTE** > ->1. This API has been deprecated. You are advised to use [off\('headersReceive'\)8+](#offheadersreceive8) instead. +>1. This API has been deprecated. You are advised to use [off('headersReceive')8+](#offheadersreceive8) instead. > >2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. @@ -277,9 +586,9 @@ Unregisters the observer for HTTP Response Header events. httpRequest.off('headerReceive'); ``` -### on\('headersReceive'\)8+ +### on('headersReceive')8+ -on\(type: 'headersReceive', callback: Callback\): void +on(type: 'headersReceive', callback: Callback\): void Registers an observer for HTTP Response Header events. @@ -300,9 +609,9 @@ httpRequest.on('headersReceive', (header) => { }); ``` -### off\('headersReceive'\)8+ +### off('headersReceive')8+ -off\(type: 'headersReceive', callback?: Callback\): void +off(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. @@ -324,9 +633,9 @@ Unregisters the observer for HTTP Response Header events. httpRequest.off('headersReceive'); ``` -### once\('headersReceive'\)8+ +### once('headersReceive')8+ -once\(type: 'headersReceive', callback: Callback\): void +once(type: 'headersReceive', callback: Callback\): void Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result. @@ -346,7 +655,146 @@ httpRequest.once('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); ``` +### on('dataReceive')10+ + +on(type: 'dataReceive', callback: Callback\): void + +Registers an observer for events indicating receiving of HTTP streaming responses. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **dataReceive**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +httpRequest.on('dataReceive', (data) => { + console.info('dataReceive length: ' + JSON.stringify(data.byteLength)); +}); +``` + +### off('dataReceive')10+ + +off(type: 'dataReceive', callback?: Callback\): void + +Unregisters the observer for events indicating receiving of HTTP streaming responses. + +>**NOTE** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataReceive**.| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataReceive'); +``` + +### on('dataEnd')10+ + +on(type: 'dataEnd', callback: Callback\): void + +Registers an observer for events indicating completion of receiving HTTP streaming responses. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **dataEnd**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +httpRequest.on('dataReceive', () => { + console.info('Receive dataEnd! '); +}); +``` +### off('dataEnd')10+ + +off(type: 'dataEnd', callback?: Callback\): void + +Unregisters the observer for events indicating completion of receiving HTTP streaming responses. + +>**NOTE** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataEnd**.| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataEnd'); +``` + +### on('dataProgress')10+ + + on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void + +Registers an observer for events indicating progress of receiving HTTP streaming responses. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **dataProgress**.| +| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.
**receiveSize**: number of received bytes.
**totalSize**: total number of bytes to be received.| + +**Example** + +```js +httpRequest.on('dataProgress', (data) => { + console.info('dataProgress:' + JSON.stringify(data)); +}); +``` + +### off('dataProgress')10+ + +off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void + +Unregisters the observer for events indicating progress of receiving HTTP streaming responses. + +>**NOTE** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataProgress**.| +| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataProgress'); +``` ## HttpRequestOptions Specifies the type and value range of the optional parameters in the HTTP request. @@ -357,13 +805,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | | extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.6+ | -| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| +| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| | usingCache9+ | boolean | No | Whether to use the cache. The default value is **true**. | | priority9+ | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | -| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | -| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | -| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | -| usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | +| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | +| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | +| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | +| usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | +| usingProxy10+ | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.
- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.
- If **usingProxy** is of the **object** type, the specified network proxy is used. | ## RequestMethod @@ -372,7 +821,7 @@ Defines an HTTP request method. **System capability**: SystemCapability.Communication.NetStack | Name | Value | Description | -| ------ | ------- | ------------------ | +| :------ | ------- | :------------------ | | OPTIONS | "OPTIONS" | OPTIONS method.| | GET | "GET" | GET method. | | HEAD | "HEAD" | HEAD method. | @@ -390,7 +839,7 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | @@ -436,9 +885,9 @@ Defines the response to an HTTP request. | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | resultType9+ | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | -| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| +| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| -| cookies8+ | Array\ | Yes | Cookies returned by the server. | +| cookies8+ | string | Yes | Cookies returned by the server. | ## http.createHttpResponseCache9+ @@ -457,7 +906,7 @@ Creates a default object to store responses to HTTP access requests. **Return value** | Type | Description | -| ---------- | ----------------------------------------------------------- | +| :---------- | :----------------------------------------------------------- | | [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| **Example** @@ -469,11 +918,11 @@ let httpResponseCache = http.createHttpResponseCache(); ## HttpResponseCache9+ -Defines an object that stores the response to an HTTP request. +Defines an object that stores the response to an HTTP request. Before invoking APIs provided by **HttpResponseCache**, you must call [createHttpResponseCache()](#httpcreatehttpresponsecache9) to create an **HttpRequestTask** object. ### flush9+ -flush(callback: AsyncCallback\): void +flush(callback: AsyncCallback\): void Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. @@ -483,23 +932,23 @@ Flushes data in the cache to the file system so that the cached data can be acce | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js httpResponseCache.flush(err => { if (err) { - console.log('flush fail'); + console.info('flush fail'); return; } - console.log('flush success'); + console.info('flush success'); }); ``` ### flush9+ -flush(): Promise\ +flush(): Promise\ Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result. @@ -509,21 +958,21 @@ Flushes data in the cache to the file system so that the cached data can be acce | Type | Description | | --------------------------------- | ------------------------------------- | -| Promise\> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** ```js httpResponseCache.flush().then(() => { - console.log('flush success'); + console.info('flush success'); }).catch(err => { - console.log('flush fail'); + console.info('flush fail'); }); ``` ### delete9+ -delete(callback: AsyncCallback\): void +delete(callback: AsyncCallback\): void Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. @@ -533,22 +982,22 @@ Disables the cache and deletes the data in it. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js httpResponseCache.delete(err => { if (err) { - console.log('delete fail'); + console.info('delete fail'); return; } - console.log('delete success'); + console.info('delete success'); }); ``` ### delete9+ -delete(): Promise\ +delete(): Promise\ Disables the cache and deletes the data in it. This API uses a promise to return the result. @@ -558,29 +1007,18 @@ Disables the cache and deletes the data in it. This API uses a promise to return | Type | Description | | --------------------------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** ```js httpResponseCache.delete().then(() => { - console.log('delete success'); + console.info('delete success'); }).catch(err => { - console.log('delete fail'); + console.info('delete fail'); }); ``` -## Error Codes - -| Error Code| Description | -| ------ | ------------------------------------------------------------ | -| -1 | Incorrect parameter. Check whether the number and type of parameters are correct. | -| 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. | -| 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. | -| 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | -| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | -| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. | - ## HttpDataType9+ Enumerates HTTP data types. @@ -588,7 +1026,7 @@ Enumerates HTTP data types. **System capability**: SystemCapability.Communication.NetStack | Name| Value| Description | -| ------------------ | -- | ----------- | +| ------------------ | -- | ----------- | | STRING | 0 | String type.| | OBJECT | 1 | Object type. | | ARRAY_BUFFER | 2 | Binary array type.| @@ -600,6 +1038,6 @@ Enumerates HTTP protocol versions. **System capability**: SystemCapability.Communication.NetStack | Name | Description | -| -------- | ----------- | +| :-------- | :----------- | | HTTP1_1 | HTTP1.1 | | HTTP2 | HTTP2 | diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index cad81d4e80c3303859274b2b79c3258bf8d2556c..0dfcc793a2d005d34501735f320e78ab421b1a08 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -3,7 +3,7 @@ The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -1818,9 +1818,9 @@ Enumerates the user authentication types. | Name | Value | Description | | ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | -| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| -| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 << 0 | Fingerprint authentication. | +| HUKS_USER_AUTH_TYPE_FACE | 1 << 1 | Facial authentication.| +| HUKS_USER_AUTH_TYPE_PIN | 1 << 2 | PIN authentication.| ## HuksAuthAccessType9+ @@ -1830,8 +1830,8 @@ Enumerates the access control types. | Name | Value | Description | | --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.| +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 << 0 | The key becomes invalid after the password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 1 << 1 | The key becomes invalid after a new biometric feature is added.| ## HuksChallengeType9+ @@ -1892,7 +1892,7 @@ Enumerates the tags used to invoke parameters. | Name | Value | Description | | -------------------------------------------- | ---------------------------------------- | -------------------------------------- | | HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | | HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | | HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | | HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | @@ -1922,7 +1922,7 @@ Enumerates the tags used to invoke parameters. | HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | | HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | | HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | | HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | | HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | | HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | @@ -2889,11 +2889,6 @@ Enumerates the error codes. | HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| | HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| | HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| | HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | | HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| | HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| @@ -2920,7 +2915,5 @@ Enumerates the error codes. | HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| | HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| | HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| | HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| | HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index cda33f5434360fe5ca3f21f9f2c0a04ad5b50474..2a85da3460cf4dff87a3076686a8b31ae136f65a 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,12 +1,12 @@ # @ohos.i18n (Internationalization) -The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. -The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. + This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. +The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. > **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). +> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). ## Modules to Import @@ -42,7 +42,7 @@ Obtains the localized script for the specified country. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -53,7 +53,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" } catch(error) { - console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -81,7 +81,7 @@ Obtains the localized script for the specified language. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -92,7 +92,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese } catch(error) { - console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -100,7 +100,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getSystemLanguages(): Array<string> -Obtains the list of system languages. +Obtains the list of system languages. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop). **System capability**: SystemCapability.Global.I18n @@ -112,7 +112,7 @@ Obtains the list of system languages. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -123,7 +123,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] } catch(error) { - console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -131,7 +131,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getSystemCountries(language: string): Array<string> -Obtains the list of countries and regions supported for the specified language. +Obtains the list of countries and regions supported for the specified language. For details about countries or regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop). **System capability**: SystemCapability.Global.I18n @@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -160,7 +160,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total } catch(error) { - console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -187,7 +187,7 @@ Checks whether the system language matches the specified region. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -198,7 +198,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let res = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { - console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -206,7 +206,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getSystemLanguage(): string -Obtains the system language. +Obtains the system language. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop). **System capability**: SystemCapability.Global.I18n @@ -218,7 +218,7 @@ Obtains the system language. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -229,7 +229,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. } catch(error) { - console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void Sets the system language. Currently, this API does not support real-time updating of the system language. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -264,7 +264,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.setSystemLanguage('zh'); // Set the current system language to zh. } catch(error) { - console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -272,7 +272,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getSystemRegion(): string -Obtains the system region. +Obtains the system region. For details about system regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop). **System capability**: SystemCapability.Global.I18n @@ -284,7 +284,7 @@ Obtains the system region. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -295,7 +295,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region. } catch(error) { - console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -305,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -319,7 +319,7 @@ Sets the system region. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -330,7 +330,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.setSystemRegion('CN'); // Set the current system region to CN. } catch(error) { - console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -338,7 +338,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getSystemLocale(): string -Obtains the system locale. +Obtains the system locale. For details about system locales, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop). **System capability**: SystemCapability.Global.I18n @@ -350,7 +350,7 @@ Obtains the system locale. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -361,7 +361,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale. } catch(error) { - console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -385,7 +385,7 @@ Sets the system locale. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -396,7 +396,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN. } catch(error) { - console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -427,7 +427,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled. } catch(error) { - console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -451,7 +451,7 @@ Sets the 24-hour clock. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -463,7 +463,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.set24HourClock(true); } catch(error) { - console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void Adds a preferred language to the specified position on the preferred language list. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -502,7 +502,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list. } catch(error) { - console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void Deletes a preferred language from the specified position on the preferred language list. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -539,7 +539,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.removePreferredLanguage(index); } catch(error) { - console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the preferred language list. +Obtains the list of preferred languages. **System capability**: SystemCapability.Global.I18n @@ -555,11 +555,11 @@ Obtains the preferred language list. | Type | Description | | ------------------- | --------- | -| Array<string> | Preferred language list.| +| Array<string> | List of preferred languages.| **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -570,7 +570,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list. } catch(error) { - console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -590,7 +590,7 @@ Obtains the first language in the preferred language list. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -601,7 +601,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list. } catch(error) { - console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -621,7 +621,7 @@ Obtains the preferred language of an application. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -632,7 +632,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application. } catch(error) { - console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -640,9 +640,9 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static setUsingLocalDigit(flag: boolean): void -Sets whether to enable the local digit switch. +Specifies whether to enable use of local digits. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -652,11 +652,11 @@ Sets whether to enable the local digit switch. | Name | Type | Mandatory | Description | | ---- | ------- | ---- | ------------------------------- | -| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| +| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -667,7 +667,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. } catch(error) { - console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -675,7 +675,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getUsingLocalDigit(): boolean -Checks whether the local digit switch is turned on. +Checks whether use of local digits is enabled. **System capability**: SystemCapability.Global.I18n @@ -687,7 +687,7 @@ Checks whether the local digit switch is turned on. **Error codes** -For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). | ID | Error Message | | ------ | ---------------------- | @@ -698,7 +698,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod try { let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled. } catch(error) { - console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -1025,7 +1025,7 @@ Checks whether the specified date in this **Calendar** object is a weekend. | Name | Type | Mandatory | Description | | ---- | ---- | ---- | ---------------------------------------- | -| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| +| date | Date | No | Specified date in this **Calendar** object. If the **date** parameter is not specified, the system checks whether the current date is a weekend.| **Return value** @@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------- | | country | string | Yes | Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. | **Example** ```js @@ -1149,7 +1149,7 @@ Obtains the home location of a phone number. ``` -## PhoneNumberFormatOptions8+ +## PhoneNumberFormatOptions9+ Defines the options for this PhoneNumberFormat object. @@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); ``` @@ -1267,7 +1267,7 @@ Obtains the index of a text object. **Example** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); let index = indexUtil.getIndex("hi"); // index = "H" ``` @@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - let iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. static getCityDisplayName(cityID: string, locale: string): string -Obtains the localized representation of a time zone city in the specified locale. +Obtains the localized display of a time zone city in the specified locale. **System capability**: SystemCapability.Global.I18n @@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9. getPreferredLanguageList(): Array<string> -Obtains the preferred language list. +Obtains the list of preferred languages. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. @@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | Preferred language list.| +| Array<string> | List of preferred languages.| **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index c675e395d694b58c2d79bbc152344f98b2505e75..3b3c16a565cca24d717a7843b08ccbb615b18c7a 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -948,8 +948,18 @@ Creates an **ImageSource** instance based on the URI. **Example** ```js -let context = featureAbility.getContext(); -let path = context.getCacheDir() + "test.jpg"; +// Stage model +const context = getContext(this); +const path = context.getCacheDir() + "/test.jpg"; +const imageSourceApi = image.createImageSource(path); +``` + +```js +// FA model +import featureAbility from '@ohos.ability.featureAbility'; + +const context = featureAbility.getContext(); +const path = context.getCacheDir() + "/test.jpg"; const imageSourceApi = image.createImageSource(path); ``` @@ -1479,8 +1489,8 @@ Creates a **PixelMap** object based on the default parameters. This API uses an ```js imageSourceApi.createPixelMap((err, pixelmap) => { - console.info('Succeeded in creating pixelmap object.'); - }) + console.info('Succeeded in creating pixelmap object.'); +}) ``` ### createPixelMap7+ @@ -1515,6 +1525,177 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => { }) ``` +### createPixelMapList10+ + +createPixelMapList(options?: DecodingOptions): Promise>; + +Creates an array of **PixelMap** objects based on image decoding parameters. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters. | + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise> | Promise used to return an array of **PixeMap** objects.| + +**Example** + +```js +let decodeOpts = { + sampleSize: 1, + editable: true, + desiredSize: { width: 198, height: 202 }, + rotate: 0, + desiredPixelFormat: RGBA_8888, + index: 0, +}; +let pixelmaplist = await imageSourceApi.createPixelMapList(decodeOpts); +``` + +### createPixelMapList10+ + +createPixelMapList(callback: AsyncCallback>): void + +Creates an array of **PixelMap** objects based on the default parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| + +**Example** + +```js +imageSourceApi.createPixelMap( pixelmaplist => { + console.info('Succeeded in creating pixelmaplist object.'); +}) +``` + +### createPixelMapList10+ + +createPixelMapList(options: DecodingOptions, callback: AsyncCallback>): void; + +Creates an array of **PixelMap** objects based on image decoding parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| options | [DecodingOptions](#decodingoptions7) | Yes| Image decoding parameters.| +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| + +**Example** + +```js +let decodeOpts = { + sampleSize: 1, + editable: true, + desiredSize: { width: 198, height: 202 }, + rotate: 0, + desiredPixelFormat: RGBA_8888, + index: 0, +}; +imageSourceApi.createPixelMap(decodeOpts, pixelmaplist => { + console.log('Succeeded in creating pixelmaplist object.'); +}) +``` + +### getDelayTime10+ + +getDelayTime(callback: AsyncCallback>): void; + +Obtains an array of delay times. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback> | Yes | Callback used to return an array of delay times.| + +**Example** + +```js +imageSourceApi.getDelayTime( delayTimes => { + console.log('Succeeded in getting delay time.'); +}); +``` + +### getDelayTime10+ + +getDelayTime(): Promise>; + +Obtains an array of delay times. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise> | Promise used to return an array of delay times.| + +**Example** + +```js +let delayTimes = await imageSourceApi.getDelayTime(); +``` + +### getFrameCount10+ + +getFrameCount(callback: AsyncCallback): void; + +Obtains the number of frames. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the number of frames.| + +**Example** + +```js +imageSourceApi.getFrameCount( frameCount => { + console.log('Succeeded in getting frame count.'); +}); +``` + +### getFrameCount10+ + +getFrameCount(): Promise\; + +Obtains the number of frames. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise\ | Promise used to return the number of frames.| + +**Example** + +```js +let frameCount = await imageSourceApi.getFrameCount(); +``` + ### release release(callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 818b1e8e324ba1ffa5aa5301dbe3843c8d4e4ba0..6001a514c8b5f07874460271d0ebce3cf96c0987 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -39,8 +39,12 @@ let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); let mode = 'rw'; -DAHelper.openFile('dataability:///com.example.DataAbility', mode, (err, data) => { - console.info('openFile err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.openFile('dataability:///com.example.DataAbility', mode, (error, data) => { + if (error && error.code !== 0) { + console.error('openFile fail, error: ${JSON.stringify(error)}'); + } else { + console.log('openFile success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -170,8 +174,12 @@ import featureAbility from '@ohos.ability.featureAbility'; let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); -DAHelper.getType('dataability:///com.example.DataAbility', (err, data) => { - console.info('getType err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.getType('dataability:///com.example.DataAbility', (error, data) => { + if (error && error.code !== 0) { + console.error('getType fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getType success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -230,8 +238,12 @@ import featureAbility from '@ohos.ability.featureAbility'; let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); -DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', 'image/*', (err, data) => { - console.info('getFileTypes err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', 'image/*', (error, data) => { + if (error && error.code !== 0) { + console.error('getFileTypes fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getFileTypes success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -290,8 +302,12 @@ import featureAbility from '@ohos.ability.featureAbility'; let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); -DAHelper.normalizeUri('dataability:///com.example.DataAbility', (err, data) => { - console.info('normalizeUri err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.normalizeUri('dataability:///com.example.DataAbility', (error, data) => { + if (error && error.code !== 0) { + console.error('normalizeUri fail, error: ${JSON.stringify(error)}'); + } else { + console.log('normalizeUri success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -349,8 +365,12 @@ import featureAbility from '@ohos.ability.featureAbility'; let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); -DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (err, data) => { - console.info('denormalizeUri err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (error, data) => { + if (error && error.code !== 0) { + console.error('denormalizeUri fail, error: ${JSON.stringify(error)}'); + } else { + console.log('denormalizeUri success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -408,8 +428,12 @@ import featureAbility from '@ohos.ability.featureAbility'; let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); -DAHelper.notifyChange('dataability:///com.example.DataAbility', (err) => { - console.info('==========================>Called=======================>'); +DAHelper.notifyChange('dataability:///com.example.DataAbility', (error) => { + if (error && error.code !== 0) { + console.error('notifyChange fail, error: ${JSON.stringify(error)}'); + } else { + console.log('notifyChange success'); + } }); ``` @@ -474,8 +498,12 @@ const valueBucket = { 'salary': 200.5, 'blobType': 'u8', }; -DAHelper.insert('dataability:///com.example.DataAbility', valueBucket, (err, data) => { - console.info('insert err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.insert('dataability:///com.example.DataAbility', valueBucket, (error, data) => { + if (error && error.code !== 0) { + console.error('insert fail, error: ${JSON.stringify(error)}'); + } else { + console.log('insert success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -544,8 +572,12 @@ let DAHelper = featureAbility.acquireDataAbilityHelper( let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, {'name': 'roe12', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}); -DAHelper.batchInsert('dataability:///com.example.DataAbility', cars, (err, data) => { - console.info('batchInsert err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.batchInsert('dataability:///com.example.DataAbility', cars, (error, data) => { + if (error && error.code !== 0) { + console.error('batchInsert fail, error: ${JSON.stringify(error)}'); + } else { + console.log('batchInsert success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -610,8 +642,12 @@ let DAHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.DataAbility' ); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.delete('dataability:///com.example.DataAbility', da, (err, data) => { - console.info('delete err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.delete('dataability:///com.example.DataAbility', da, (error, data) => { + if (error && error.code !== 0) { + console.error('delete fail, error: ${JSON.stringify(error)}'); + } else { + console.log('delete success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -682,8 +718,12 @@ const va = { 'blobType': 'u8', }; let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.update('dataability:///com.example.DataAbility', va, da, (err, data) => { - console.info('update err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.update('dataability:///com.example.DataAbility', va, da, (error, data) => { + if (error && error.code !== 0) { + console.error('update fail, error: ${JSON.stringify(error)}'); + } else { + console.log('update success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -756,8 +796,12 @@ let DAHelper = featureAbility.acquireDataAbilityHelper( ); let cars=new Array('value1', 'value2', 'value3', 'value4'); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.query('dataability:///com.example.DataAbility', cars, da, (err, data) => { - console.info('query err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +DAHelper.query('dataability:///com.example.DataAbility', cars, da, (error, data) => { + if (error && error.code !== 0) { + console.error('query fail, error: ${JSON.stringify(error)}'); + } else { + console.log('query success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -827,12 +871,12 @@ let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.jsapidemo.UserDataAbility' ); dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', - 'method', 'arg', {'key1':'value1'}, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ${err}'); - return; + 'method', 'arg', {'key1':'value1'}, (error, data) => { + if (error && error.code !== 0) { + console.error('call fail, error: ${JSON.stringify(error)}'); + } else { + console.log('call success, data: ${JSON.stringify(data)}'); } - console.info('Operation succeeded: ${data}'); }); ``` @@ -869,9 +913,9 @@ let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( ); dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', 'method', 'arg', {'key1':'value1'}).then((data) => { - console.info('Operation succeeded: ${data}'); + console.info('call success, data: ${data}'); }).catch((error) => { - console.error('Operation failed. Cause: ${error}'); + console.error('call failed, error: ${error}'); }); ``` @@ -901,12 +945,12 @@ let op=new Array(); let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.jsapidemo.UserDataAbility' ); -dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ${err}'); - return; +dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (error, data) => { + if (error && error.code !== 0) { + console.error('executeBatch fail, error: ${JSON.stringify(error)}'); + } else { + console.log('executeBatch success, data: ${JSON.stringify(data)}'); } - console.info('Operation succeeded: ${data}'); }); ``` @@ -942,9 +986,9 @@ let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( 'dataability:///com.example.jsapidemo.UserDataAbility' ); dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op).then((data) => { - console.info('Operation succeeded: ${data}'); + console.info('executeBatch success, data: ${data}'); }).catch((error) => { - console.error('Operation failed. Cause: ${error}'); + console.error('executeBatch failed, error: ${error}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 2b90cd54ed08d8a8c954c0598049019d5673b2fa..6dffdaefc00b58a14fce5820b969866b3c564a0b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -27,11 +27,9 @@ function executeBatchOperation() { DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); if (DAHelper === null) { console.error('DAHelper is null'); - return; } } catch (err) { console.error('acquireDataAbilityHelper fail, error: ${JSON.stringify(err)}'); - return; } let valueBucket = { diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index c7462af45a51405c58e90e7811ba2e1078d1d177..80fcf902d83b94b26cd7f667d971855d4be959b9 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -36,11 +36,14 @@ let startAbilityParameter = { }; try { - featureAbility.startAbility(startAbilityParameter, (err, data) => { - console.log('errCode : ${JSON.stringify(err)}'); - console.log('data : ${JSON.stringify(data)}'); + featureAbility.startAbility(startAbilityParameter, (error, data) => { + if (error && error.code !== 0) { + console.error('startAbility fail, error: ${JSON.stringify(error)}'); + } else { + console.log('startAbility success, data: ${JSON.stringify(data)}'); + } }); } catch(error) { - console.log('startAbility error: ${JSON.stringify(error)}'); + console.error('startAbility error: ${JSON.stringify(error)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md index 4b22df32e51f014e4697c88dab634fa234407760..79fcf1af73e773ca24167bef9f2aa4052d5293a2 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -41,8 +41,12 @@ If this API is called for the first time, a root directory will be created. ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getOrCreateLocalDir((err, data)=>{ - console.info('getOrCreateLocalDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getOrCreateLocalDir((error, data)=>{ + if (error && error.code !== 0) { + console.error('getOrCreateLocalDir fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getOrCreateLocalDir success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -97,8 +101,12 @@ import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle.bundleManager'; let context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ - context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (err, data) =>{ - console.info('verifyPermission err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); + context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (error, data) =>{ + if (error && error.code !== 0) { + console.error('verifyPermission fail, error: ${JSON.stringify(error)}'); + } else { + console.log('verifyPermission success, data: ${JSON.stringify(data)}'); + } }); }); ``` @@ -126,8 +134,12 @@ Verifies whether the current PID and UID have the given permission. This API use ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.verifyPermission('com.example.permission', (err, data) =>{ - console.info('verifyPermission err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.verifyPermission('com.example.permission', (error, data) =>{ + if (error && error.code !== 0) { + console.error('verifyPermission fail, error: ${JSON.stringify(error)}'); + } else { + console.log('verifyPermission success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -193,8 +205,12 @@ context.requestPermissionsFromUser( 'com.example.permission4', 'com.example.permission5'], 1, - (err, data) => { - console.info('requestPermissionsFromUser err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('requestPermissionsFromUser fail, error: ${JSON.stringify(error)}'); + } else { + console.log('requestPermissionsFromUser success, data: ${JSON.stringify(data)}'); + } } ); ``` @@ -259,8 +275,12 @@ Obtains information about the current application. This API uses an asynchronous ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getApplicationInfo((err, data) => { - console.info('getApplicationInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getApplicationInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getApplicationInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getApplicationInfo success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -311,8 +331,12 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getBundleName((err, data) => { - console.info('getBundleName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getBundleName((error, data) => { + if (error && error.code !== 0) { + console.error('getBundleName fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getBundleName success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -361,8 +385,12 @@ Obtains the display orientation of this ability. This API uses an asynchronous c ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getDisplayOrientation((err, data) => { - console.info('getDisplayOrientation err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getDisplayOrientation((error, data) => { + if (error && error.code !== 0) { + console.error('getDisplayOrientation fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getDisplayOrientation success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -409,8 +437,12 @@ Obtains the external cache directory of the application. This API uses an asynch ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getExternalCacheDir((err, data) => { - console.info('getExternalCacheDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getExternalCacheDir((error, data) => { + if (error && error.code !== 0) { + console.error('getExternalCacheDir fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getExternalCacheDir success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -460,8 +492,8 @@ import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; let context = featureAbility.getContext(); let orientation = bundle.DisplayOrientation.UNSPECIFIED; -context.setDisplayOrientation(orientation, (err) => { - console.info('setDisplayOrientation err: ${JSON.stringify(err)}'); +context.setDisplayOrientation(orientation, (error) => { + console.error('setDisplayOrientation fail, error: ${JSON.stringify(error)}'); }); ``` @@ -513,8 +545,8 @@ Sets whether to show this feature at the top of the lock screen so that the feat import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); let show = true; -context.setShowOnLockScreen(show, (err) => { - console.info('setShowOnLockScreen err: ${JSON.stringify(err)}'); +context.setShowOnLockScreen(show, (error) => { + console.error('setShowOnLockScreen fail, error: ${JSON.stringify(error)}'); }); ``` @@ -570,8 +602,8 @@ Sets whether to wake up the screen when this feature is restored. This API uses import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); let wakeUp = true; -context.setWakeUpScreen(wakeUp, (err) => { - console.info('setWakeUpScreen err: ${JSON.stringify(err)}'); +context.setWakeUpScreen(wakeUp, (error) => { + console.error('setWakeUpScreen fail, error: ${JSON.stringify(error)}'); }); ``` @@ -628,8 +660,12 @@ Obtains information about the current process, including the PID and process nam ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getProcessInfo((err, data) => { - console.info('getProcessInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getProcessInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getProcessInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getProcessInfo success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -682,8 +718,12 @@ This API is available only to Page abilities. ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getElementName((err, data) => { - console.info('getElementName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getElementName((error, data) => { + if (error && error.code !== 0) { + console.error('getElementName fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getElementName success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -734,8 +774,12 @@ Obtains the name of the current process. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getProcessName((err, data) => { - console.info('getProcessName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getProcessName((error, data) => { + if (error && error.code !== 0) { + console.error('getProcessName fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getProcessName success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -786,8 +830,12 @@ Obtains the bundle name of the caller ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getCallingBundle((err, data) => { - console.info('getCallingBundle err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getCallingBundle((error, data) => { + if (error && error.code !== 0) { + console.error('getCallingBundle fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getCallingBundle success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -836,8 +884,12 @@ Obtains the cache directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getCacheDir((err, data) => { - console.info('getCacheDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getCacheDir((error, data) => { + if (error && error.code !== 0) { + console.error('getCacheDir fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getCacheDir success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -884,8 +936,12 @@ Obtains the file directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getFilesDir((err, data) => { - console.info('getFilesDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getFilesDir((error, data) => { + if (error && error.code !== 0) { + console.error('getFilesDir fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getFilesDir success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -934,8 +990,12 @@ If the distributed file path does not exist, the system will create one and retu ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getOrCreateDistributedDir((err, data) => { - console.info('getOrCreateDistributedDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getOrCreateDistributedDir((error, data) => { + if (error && error.code !== 0) { + console.error('getOrCreateDistributedDir fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getOrCreateDistributedDir success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -984,8 +1044,12 @@ Obtains the application type. This API uses an asynchronous callback to return t ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getAppType((err, data) => { - console.info('getAppType err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getAppType((error, data) => { + if (error && error.code !== 0) { + console.error('getAppType fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getAppType success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -1032,8 +1096,12 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getHapModuleInfo((err, data) => { - console.info('getHapModuleInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getHapModuleInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getHapModuleInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getHapModuleInfo success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -1080,8 +1148,12 @@ Obtains the version information of the application. This API uses an asynchronou ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getAppVersionInfo((err, data) => { - console.info('getAppVersionInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getAppVersionInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getAppVersionInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getAppVersionInfo success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -1128,8 +1200,12 @@ Obtains information about this ability. This API uses an asynchronous callback t ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getAbilityInfo((err, data) => { - console.info('getAbilityInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getAbilityInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getAbilityInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getAbilityInfo success, data: ${JSON.stringify(data)}'); + } }); ``` @@ -1197,8 +1273,12 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.isUpdatingConfigurations((err, data) => { - console.info('isUpdatingConfigurations err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.isUpdatingConfigurations((error, data) => { + if (error && error.code !== 0) { + console.error('isUpdatingConfigurations fail, error: ${JSON.stringify(error)}'); + } else { + console.log('isUpdatingConfigurations success, data: ${JSON.stringify(data)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md index d210666803caa4e6d7e2571badacca9072f725a6..886cc755ef0939723d9c23bc612fe37ce0f7bc55 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -18,9 +18,11 @@ The **ProcessInfo** module defines process information. You can use [getProcessI import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -context.getProcessInfo((err, data) => { - if (err.code !== 0) { - console.info('getProcessInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); +context.getProcessInfo((error, data) => { + if (error && error.code !== 0) { + console.error('getProcessInfo fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getProcessInfo success, data: ${JSON.stringify(data)}'); let pid = data.pid; let processName = data.processName; } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..ff2ca7a3df236c2bf50ab883de28cae0b0599259 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md @@ -0,0 +1,24 @@ +# WorkSchedulerExtensionContext + +The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility. + +This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Usage + +The context is obtained through a WorkSchedulerExtensionAbility child class instance. + +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + +class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext. + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 051aa07c40253bc6805c57fcdf65aad84f401713..550e888888a944644c79cefec596c0f5df28ca64 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -11,8 +11,6 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**. ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; - -let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ## AbilityDelegator @@ -492,8 +490,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => { - console.info('doAbilityForeground callback'); + abilityDelegator.doAbilityForeground(ability, (err : any) => { + console.info("doAbilityForeground callback"); }); }); ``` @@ -528,8 +526,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityForeground(ability).then((data : any) => { - console.info('doAbilityForeground promise'); + abilityDelegator.doAbilityForeground(ability).then(() => { + console.info("doAbilityForeground promise"); }); }); ``` @@ -559,8 +557,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => { - console.info('doAbilityBackground callback'); + abilityDelegator.doAbilityBackground(ability, (err : any) => { + console.info("doAbilityBackground callback"); }); }); ``` @@ -595,8 +593,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityBackground(ability).then((data : any) => { - console.info('doAbilityBackground promise'); + abilityDelegator.doAbilityBackground(ability).then(() => { + console.info("doAbilityBackground promise"); }); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index 1069fcf2d43c9675ff70efd2c0e2756475db312e..e64c3175c7934190d70af04156c149741c87697c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -34,7 +34,7 @@ Describes an ability monitor. import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { - console.info('onAbilityCreateCallback'); + console.info('onAbilityCreateCallback, data: ${JSON.stringify(data)}'); } let monitor = { @@ -44,7 +44,9 @@ let monitor = { }; let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.addAbilityMonitor(monitor, (err : any) => { - console.info('addAbilityMonitor callback'); +abilityDelegator.addAbilityMonitor(monitor, (error : any) => { + if (error && error.code !== 0) { + console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 8340c33dbaa77848d90200e37b5ee309efe53697..f041998eb633cf8d00b45613b666ca563189dd77 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -30,16 +30,20 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( ```ts import abilitymanager from '@ohos.app.ability.abilityManager'; -abilitymanager.getAbilityRunningInfos((err,data) => { - console.log('getAbilityRunningInfos err: ${err}, data: ${JSON.stringify(data)}'); - for (let i = 0; i < data.length; i++) { - let abilityinfo = data[i]; - console.log('abilityinfo.ability: ${JSON.stringify(abilityinfo.ability)}'); - console.log('abilityinfo.pid: ${JSON.stringify(abilityinfo.pid)}'); - console.log('abilityinfo.uid: ${JSON.stringify(abilityinfo.uid)}'); - console.log('abilityinfo.processName: ${JSON.stringify(abilityinfo.processName)}'); - console.log('abilityinfo.startTime: ${JSON.stringify(abilityinfo.startTime)}'); - console.log('abilityinfo.abilityState: ${JSON.stringify(abilityinfo.abilityState)}'); +abilitymanager.getAbilityRunningInfos((error, data) => { + if (error && error.code !== 0) { + console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); + for (let i = 0; i < data.length; i++) { + let abilityinfo = data[i]; + console.log('abilityinfo.ability: ${JSON.stringify(abilityinfo.ability)}'); + console.log('abilityinfo.pid: ${JSON.stringify(abilityinfo.pid)}'); + console.log('abilityinfo.uid: ${JSON.stringify(abilityinfo.uid)}'); + console.log('abilityinfo.processName: ${JSON.stringify(abilityinfo.processName)}'); + console.log('abilityinfo.startTime: ${JSON.stringify(abilityinfo.startTime)}'); + console.log('abilityinfo.abilityState: ${JSON.stringify(abilityinfo.abilityState)}'); + } } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index 896b619f524ccc98b1150949b44fba3878bd268a..90fa9dc102e3f38498451bcf23a117321be08be9 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -20,6 +20,10 @@ let monitor = { let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { - console.info('stageMonitor waitAbilityStageMonitor, abilityStage = ${JSON.stringify(data)}'); + if (error && error.code !== 0) { + console.error('waitAbilityStageMonitor fail, error: ${JSON.stringify(error)}'); + } else { + console.log('waitAbilityStageMonitor success, data: ${JSON.stringify(data)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 1263f44e2db490c648decd54b93ba831a9a57e72..92450992f6d642dc1583f3147827a94622bcc96a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -1,4 +1,4 @@ -# AccessibilityExtensionContext +# AccessibilityExtensionContext (Accessibility Extension Context) The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. @@ -703,10 +703,10 @@ try { console.log('get attribute value by name success'); attributeValue = data; }).catch((err) => { - console.log('failed to get attribute value, because ${JSON.stringify(err)}'); + console.error('failed to get attribute value, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to get attribute value, because ${JSON.stringify(exception)}'); + console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` ## AccessibilityElement.attributeValue @@ -749,7 +749,7 @@ try { console.info('get attribute value success'); }); } catch (exception) { - console.log('failed to get attribute value, because ${JSON.stringify(exception)}'); + console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` ## actionNames @@ -775,7 +775,7 @@ rootElement.actionNames().then((data) => { console.log('get action names success'); actionNames = data; }).catch((err) => { - console.log('failed to get action names because ${JSON.stringify(err)}'); + console.error('failed to get action names because ${JSON.stringify(err)}'); }); ``` ## actionNames @@ -843,10 +843,10 @@ try { rootElement.performAction('action').then((data) => { console.info('perform action success'); }).catch((err) => { - console.log('failed to perform action, because ${JSON.stringify(err)}'); + console.error('failed to perform action, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to perform action, because ${JSON.stringify(exception)}'); + console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## performAction @@ -885,7 +885,7 @@ try { console.info('perform action success'); }); } catch (exception) { - console.log('failed to perform action, because ${JSON.stringify(exception)}'); + console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## performAction @@ -929,7 +929,7 @@ try { console.info('perform action success'); }); } catch (exception) { - console.log('failed to perform action, because ${JSON.stringify(exception)}'); + console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## findElement('content') @@ -965,10 +965,10 @@ try { elements = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ${JSON.stringify(err)}'); + console.error('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('content') @@ -1004,7 +1004,7 @@ try { console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusType') @@ -1040,10 +1040,10 @@ try { element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ${JSON.stringify(err)}'); + console.error('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusType') @@ -1079,7 +1079,7 @@ try { console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusDirection') @@ -1115,10 +1115,10 @@ try { element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ${JSON.stringify(err)}'); + console.error('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusDirection') @@ -1154,6 +1154,6 @@ try { console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ${JSON.stringify(exception)}'); + console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index c19d499f4a28f1d68817ef517ebeb0dc5ff0e807..3687950d91688181565b8f8cb01f8538e9e77489 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -83,7 +83,7 @@ export default class EntryAbility extends UIAbility { let applicationContext = this.context.getApplicationContext(); // 2. Use applicationContext to register a listener for the ability lifecycle in the application. lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback); - console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId)); + console.log('registerAbilityLifecycleCallback lifecycleId: ${lifecycleId)}'); } } ``` @@ -114,9 +114,13 @@ let lifecycleId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - console.log('stage applicationContext: ' + applicationContext); - applicationContext.off(type: 'abilityLifecycle', lifecycleId, (error, data) => { - console.log('unregisterAbilityLifecycleCallback success, err: ' + JSON.stringify(error)); + console.log('stage applicationContext: ${applicationContext}'); + applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => { + if (error && error.code !== 0) { + console.error('unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}'); + } else { + console.log('unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}'); + } }); } } @@ -147,8 +151,8 @@ let lifecycleId; export default class MyAbility extends Ability { onDestroy() { let applicationContext = this.context.getApplicationContext(); - console.log('stage applicationContext: ' + applicationContext); - applicationContext.off(type: 'abilityLifecycle', lifecycleId); + console.log('stage applicationContext: ${applicationContext}'); + applicationContext.off('abilityLifecycle', lifecycleId); } } ``` @@ -185,19 +189,19 @@ export default class EntryAbility extends UIAbility { onCreate() { console.log('MyAbility onCreate') globalThis.applicationContext = this.context.getApplicationContext(); - let EnvironmentCallback = { + let environmentCallback = { onConfigurationUpdated(config){ - console.log('onConfigurationUpdated config:' + JSON.stringify(config)); + console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); }, onMemoryLevel(level){ - console.log('onMemoryLevel level:' + level); + console.log('onMemoryLevel level: ${level}'); } - } + }; // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - callbackId = applicationContext.on('environment', EnvironmentCallback); - console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId)); + // 2. Use applicationContext to register a listener for system environment changes. + callbackId = applicationContext.on('environment', environmentCallback); + console.log('registerEnvironmentCallback callbackId: ${callbackId}'); } } ``` @@ -229,7 +233,11 @@ export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); applicationContext.off('environment', callbackId, (error, data) => { - console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error)); + if (error && error.code !== 0) { + console.error('unregisterEnvironmentCallback fail, err: ${JSON.stringify(error)}'); + } else { + console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}'); + } }); } } @@ -290,7 +298,7 @@ let applicationContext = this.context.getApplicationContext(); applicationContext.getRunningProcessInformation().then((data) => { console.log('The process running information is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('error: ${JSON.stringify(error)}'); + console.error('error: ${JSON.stringify(error)}'); }); ``` @@ -364,7 +372,9 @@ Kills all the processes where the application is located. This API uses an async ```ts let applicationContext = this.context.getApplicationContext(); -applicationContext.killAllProcesses(err => { - console.error('killAllProcesses result: ${JSON.stringify(err)}'); +applicationContext.killAllProcesses(error => { + if (error && error.code !== 0) { + console.error('killAllProcesses fail, error: ${JSON.stringify(error)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index eb9ed63890d99338a57c18613eb37c59f753be0e..4b0dc98ea7bb95c66ebfe29cf938d376419a46f0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -62,7 +62,7 @@ let bundleContext; try { bundleContext = this.context.createBundleContext('com.example.test'); } catch (error) { - console.log('createBundleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('createBundleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` @@ -101,7 +101,7 @@ let moduleContext; try { moduleContext = this.context.createModuleContext('entry'); } catch (error) { - console.log('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` @@ -141,7 +141,7 @@ let moduleContext; try { moduleContext = this.context.createModuleContext('com.example.test', 'entry'); } catch (error) { - console.log('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` @@ -166,6 +166,6 @@ let applicationContext; try { applicationContext = this.context.getApplicationContext(); } catch (error) { - console.log('getApplicationContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('getApplicationContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index 448212035ad08f63371b001ab305cadf0153c807..1ada23c202d88e7afa85da2a021130be1a434bc0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -38,7 +38,7 @@ Called when the mission continuation is complete. distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { if (error && error.code) { - console.log('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } console.log('continueMission finished'); }); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index 424456ba9bf4d52f0e9696b4268fe743b8a0fd8e..5c3200aedcf788ea30bba84156fd623ae7a2138f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -33,7 +33,7 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { if (error && error.code) { - console.log('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } console.log('continueMission finished'); }); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 85b9503b48dc15a49c19cd74be00f071e93e3969..3d3e1d3190082c757a442371fa671576cc5a6758 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -23,13 +23,13 @@ import errorManager from '@ohos.app.ability.errorManager'; let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg); + console.error('onUnhandledException, errorMsg: ', errorMsg); } }; try { errorManager.on('error', observer); } catch (error) { - console.log('registerErrorObserver failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('registerErrorObserver failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 1e3003c9410c1bea9f0e8ef4f930966e9a6e5f4e..17441d6bb281e87f0ae45c8a4764f657809b7bee 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -33,7 +33,7 @@ let upperLimit = 1; function getExtensionInfos() { abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { if (error && error.code) { - console.log('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index 71d91c1fab2864341105c2ae3a636133c8a33208..c679a6fe5c87954f27b76531a3d21a3c3726e410 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -67,7 +67,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { }; this.context.startAbility(want, (error, data) => { if (error) { - console.log('FormExtensionContext startAbility, error:${JSON.stringify(error)}'); + console.error('FormExtensionContext startAbility, error:${JSON.stringify(error)}'); } else { console.log('FormExtensionContext startAbility success'); } @@ -118,7 +118,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { this.context.startAbility(want).then(() => { console.info('StartAbility Success'); }).catch((error) => { - console.info('StartAbility failed'); + console.error('StartAbility failed'); }); } }; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index ff8c880a0db0f67a8fc184bb9986245bfd9ad7af..d7cfc2a25b572c3178c3da71d9e04c5fb9c3a8af 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -25,7 +25,7 @@ try { missionManager.getMissionInfo('', 1, (error, data) => { if (error.code) { // Process service logic errors. - console.log('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } @@ -39,6 +39,6 @@ try { console.log('getMissionInfo continuable is: ${JSON.stringify(data.continuable)}'); }); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index 84aa5294ce48be5388103945bfb417284cfa297e..9386b6f5b9b84129d6db9e86f944f01cf679d538 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -31,9 +31,13 @@ let listener = { onMissionMovedToFront: function (mission) { console.log('onMissionMovedToFront mission: ${JSON.stringify(mission)}'); }, - onMissionIconUpdated: function (mission, icon) { - console.log('onMissionIconUpdated mission: ${JSON.stringify(mission)}'); + onMissionLabelUpdated: function (mission) { + console.log('onMissionLabelUpdated mission: ' + JSON.stringify(mission)); }, + onMissionIconUpdated: function (mission, icon) { + console.log('onMissionIconUpdated mission: ' + JSON.stringify(mission)); + console.log('onMissionIconUpdated icon: ' + JSON.stringify(icon)); + }, onMissionClosed: function (mission) { console.log('onMissionClosed mission: ${JSON.stringify(mission)}'); } @@ -42,6 +46,6 @@ let listener = { try { let listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.log('error: ${paramError.code}, ${paramError.message}'); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md index 40e8cc3f92791f09b505912b3a391080aa6465bc..143c640c90657ef42cc45e4dc3a83e378f45507d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -21,8 +21,12 @@ let missionParameter = { }; try { distributedMissionManager.startSyncRemoteMissions(missionParameter, - (err, data) => { - console.log('startSyncRemoteMissions, data: ${JSON.stringify(data)}'); + (error, data) => { + if (error && error.code !== 0) { + console.error('startSyncRemoteMissions fail, error: ${JSON.stringify(error)}'); + } else { + console.log('startSyncRemoteMissions success, data: ${JSON.stringify(data)}'); + } } ); } catch (err) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md index 19c8f42e7de0b8c354c14d44300a65ce7f0ac208..d2ee664b5fade510aabf9a0113e4ce406e2f6af4 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md @@ -14,7 +14,11 @@ The process information is obtained by calling [getRunningProcessInformation](js import appManager from '@ohos.app.ability.appManager'; appManager.getRunningProcessInformation((error, data) => { - console.log('error: ${error.code}, data: ${JSON.stringify(data)}'); + if (error && error.code !== 0) { + console.error('getRunningProcessInformation fail, error: ${JSON.stringify(error)}'); + } else { + console.log('getRunningProcessInformation success, data: ${JSON.stringify(data)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index f0025296af4ced3c2c7c344e395478df608366a5..b1441077dc9b63aafab110388ad11114aa62796a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -28,6 +28,6 @@ import appManager from '@ohos.app.ability.appManager'; appManager.getProcessRunningInfos().then((data) => { console.log('success: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('failed: ${JSON.stringify(error)}'); + console.error('failed: ${JSON.stringify(error)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index 6203c272773910aeab2b6f29041ec4aa21168872..687ccf64618e815fe3f19d261340fcb11fb1ae87 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -77,7 +77,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. this.context.startAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -85,7 +85,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -155,11 +155,11 @@ Starts an ability. This API uses a promise to return the result. }) .catch((error) => { // Process service logic errors. - console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -167,7 +167,7 @@ Starts an ability. This API uses a promise to return the result. startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -221,7 +221,7 @@ Starts an ability with the start options specified. This API uses an asynchronou this.context.startAbility(want, options, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -229,7 +229,7 @@ Starts an ability with the start options specified. This API uses an asynchronou }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -295,7 +295,7 @@ Observe the following when using this API: this.context.startAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -303,7 +303,7 @@ Observe the following when using this API: }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -373,7 +373,7 @@ Observe the following when using this API: this.context.startAbilityWithAccount(want, accountId, options, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -381,7 +381,7 @@ Observe the following when using this API: }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -461,11 +461,11 @@ Observe the following when using this API: }) .catch((error) => { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -516,7 +516,7 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to this.context.startServiceExtensionAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -524,7 +524,7 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -584,11 +584,11 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu }) .catch((error) => { // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -645,7 +645,7 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -653,7 +653,7 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -718,11 +718,11 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use }) .catch((error) => { // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -770,7 +770,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch this.context.stopServiceExtensionAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -778,7 +778,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -835,11 +835,11 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise }) .catch((error) => { // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -892,7 +892,7 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code), error.message: ${JSON.stringify(error.message)}'); + console.error('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code), error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -900,7 +900,7 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -962,11 +962,11 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec }) .catch((error) => { // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1003,7 +1003,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re this.context.terminateSelf((error) => { if (error.code) { // Process service logic errors. - console.log('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -1046,7 +1046,7 @@ Terminates this ability. This API uses a promise to return the result. console.log('terminateSelf succeed'); }).catch((error) => { // Process service logic errors. - console.log('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); ``` @@ -1095,7 +1095,7 @@ Connects this ability to a ServiceAbility. let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } + onFailed(code) { console.error('----------- onFailed -----------') } }; let connection = null; @@ -1103,7 +1103,7 @@ Connects this ability to a ServiceAbility. connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1164,7 +1164,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1206,7 +1206,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous this.context.disconnectServiceExtensionAbility(connection, (error) => { if (error.code) { // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -1214,7 +1214,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1265,11 +1265,11 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret }) .catch((error) => { // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1337,11 +1337,11 @@ Observe the following when using this API: console.log('startAbilityByCall succeed'); }).catch((error) => { // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1369,10 +1369,10 @@ Observe the following when using this API: console.log('startAbilityByCall succeed'); }).catch((error) => { // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 435d799676e7924e7366fdbec93373f55313a86d..ca376d9776ffc064b82468e7c3af596a86faba53 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -24,8 +24,11 @@ let abilityDelegator; let cmd = 'cmd'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info('executeShellCommand callback, result: ', err); - console.info('executeShellCommand callback, data: ', data); +abilityDelegator.executeShellCommand(cmd, (error: any, data: any) => { + if (error && error.code !== 0) { + console.error('executeShellCommand fail, error: ${JSON.stringify(error)}'); + } else { + console.log('executeShellCommand success, data: ${JSON.stringify(data)}'); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index f735fb4b0f84720e1150f219b04ff0b79e63b3ed..9960a9bbedd04f2ceb18c3b7d34731df1689228a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -1916,7 +1916,7 @@ Sets a label for this UIAbility in the mission. This API uses a promise to retur setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; -Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. +Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. The maximum size of the icon is 600 MB. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1966,7 +1966,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call setMissionIcon(icon: image.PixelMap): Promise\; -Sets an icon for this ability in the mission. This API uses a promise to return the result. +Sets an icon for this ability in the mission. This API uses a promise to return the result. The maximum size of the icon is 600 MB. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2112,7 +2112,7 @@ try { return; } // Carry out normal service processing. - console.info('requestDialogService succeed, result = ' + JSON.stringify(result)); + console.info('requestDialogService succeed, result = ${JSON.stringify(result)}'); }); } catch (err) { // Process input parameter errors. @@ -2160,7 +2160,7 @@ try { this.context.requestDialogService(want) .then((result) => { // Carry out normal service processing. - console.info('requestDialogService succeed, result = ' + JSON.stringify(result)); + console.info('requestDialogService succeed, result = ${JSON.stringify(result)}'); }) .catch((err) => { // Process service logic errors. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md index 602766048157ebee6dfaee6192a7120f051c00dc..b4818183f77657d3852de06570e199086dc70941 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @@ -58,7 +58,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. this.context.startAbility(want, options, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -110,7 +110,7 @@ Starts an ability. This API uses a promise to return the result. }) .catch((error) => { // Process service logic errors. - console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.error('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md new file mode 100644 index 0000000000000000000000000000000000000000..a73c80d7c5fa09e19f901b3c947f445eb61989e1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md @@ -0,0 +1,11 @@ +# CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md new file mode 100644 index 0000000000000000000000000000000000000000..94963860fe1b57a6abfd6fff6fdba38816a63294 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md @@ -0,0 +1,13 @@ +# CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..2b9db9ec46f479d5d0607c33f07601b1ef721446 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md @@ -0,0 +1,11 @@ +# CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of a device on the same network. | +| userId | number | Yes | No | User ID. The value must be an existing user ID in the system. If this parameter is not specified, the default value, which is the ID of the current user, will be used. | +| priority | number | Yes | No | Subscriber priority. The value ranges from –100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md new file mode 100644 index 0000000000000000000000000000000000000000..18eeac506b75dc96b27b56b9369070215ff8892a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -0,0 +1,742 @@ +# CommonEventSubscriber + +## getCode + +```ts +getCode(callback: AsyncCallback): void +``` + +Obtains the code of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Common event code.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for result code obtaining of an ordered common event. +function getCodeCB(err, code) { + if (err.code) { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getCode " + JSON.stringify(code)); + } +} +subscriber.getCode(getCodeCB); +``` + +## getCode + +```ts +getCode(): Promise +``` + +Obtains the code of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Common event code.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.getCode().then((code) => { + console.info("getCode " + JSON.stringify(code)); +}).catch((err) => { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setCode + +```ts +setCode(code: number, callback: AsyncCallback): void +``` + +Sets the code for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Common event code. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for result code setting of an ordered common event. +function setCodeCB(err) { + if (err.code) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCB); +``` + +## setCode + +```ts +setCode(code: number): Promise +``` + +Sets the code for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| code | number | Yes | Common event code.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getData + +```ts +getData(callback: AsyncCallback): void +``` + +Obtains the data of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Common event data.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for result data obtaining of an ordered common event. +function getDataCB(err, data) { + if (err.code) { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getData " + JSON.stringify(data)); + } +} +subscriber.getData(getDataCB); +``` + +## getData + +```ts +getData(): Promise +``` + +Obtains the data of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | ------------------ | +| Promise\ | Common event data.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.getData().then((data) => { + console.info("getData " + JSON.stringify(data)); +}).catch((err) => { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setData + +setData(data: string, callback: AsyncCallback\): void + +Sets the data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| data | string | Yes | Common event data. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for result data setting of an ordered common event +function setDataCB(err) { + if (err.code) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCB); +``` + +## setData + +```ts +setData(data: string): Promise +``` + +Sets the data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| data | string | Yes | Common event data.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setCodeAndData + +```ts +setCodeAndData(code: number, data: string, callback:AsyncCallback): void +``` + +Sets the code and data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Common event code. | +| data | string | Yes | Common event data. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for code and data setting of an ordered common event. +function setCodeDataCB(err) { + if (err.code) { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); +``` + +## setCodeAndData + +```ts +setCodeAndData(code: number, data: string): Promise +``` + +Sets the code and data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| code | number | Yes | Common event code.| +| data | string | Yes | Common event data.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## isOrderedCommonEvent + +```ts +isOrderedCommonEvent(callback: AsyncCallback): void +``` + +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the common event is an ordered one; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is an ordered one. +function isOrderedCB(err, isOrdered) { + if (err.code) { + console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCB); +``` + +## isOrderedCommonEvent + +```ts +isOrderedCommonEvent(): Promise +``` + +Checks whether this common event is an ordered one. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Returns **true** if the common event is an ordered one; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## isStickyCommonEvent + +```ts +isStickyCommonEvent(callback: AsyncCallback): void +``` + +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCB(err, isSticky) { + if (err.code) { + console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCB); +``` + +## isStickyCommonEvent + +```ts +isStickyCommonEvent(): Promise +``` + +Checks whether this common event is a sticky one. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## abortCommonEvent + +```ts +abortCommonEvent(callback: AsyncCallback): void +``` + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for common event aborting. +function abortCB(err) { + if (err.code) { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCB); +``` + +## abortCommonEvent + +```ts +abortCommonEvent(): Promise +``` + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## clearAbortCommonEvent + +```ts +clearAbortCommonEvent(callback: AsyncCallback): void +``` + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for clearing the aborted state of the current common event. +function clearAbortCB(err) { + if (err.code) { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCB); +``` + +## clearAbortCommonEvent + +```ts +clearAbortCommonEvent(): Promise +``` + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getAbortCommonEvent + +```ts +getAbortCommonEvent(callback: AsyncCallback): void +``` + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is in the aborted state. +function getAbortCB(err, abortEvent) { + if (err.code) { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent " + abortEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCB); +``` + +## getAbortCommonEvent + +```ts +getAbortCommonEvent(): Promise +``` + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | ---------------------------------- | +| Promise\ | Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.getAbortCommonEvent().then((abortEvent) => { + console.info("abortCommonEvent " + JSON.stringify(abortEvent)); +}).catch((err) => { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getSubscribeInfo + +```ts +getSubscribeInfo(callback: AsyncCallback): void +``` + +Obtains the subscriber information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)> | Yes | Callback used to return the subscriber information.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for subscriber information obtaining. +function getCB(err, subscribeInfo) { + if (err.code) { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); + } +} +subscriber.getSubscribeInfo(getCB); +``` + +## getSubscribeInfo + +```ts +getSubscribeInfo(): Promise +``` + +Obtains the subscriber information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)> | Promise used to return the subscriber information.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.getSubscribeInfo().then((subscribeInfo) => { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); +}).catch((err) => { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## finishCommonEvent9+ + +```ts +finishCommonEvent(callback: AsyncCallback): void +``` + +Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +// Callback for ordered common event finishing. +function finishCB(err) { + if (err.code) { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); +} else { + console.info("FinishCommonEvent"); +} + +subscriber.finishCommonEvent(finishCB); +``` + +## finishCommonEvent9+ + +```ts +finishCommonEvent(): Promise +``` + +Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let subscriber; // Subscriber object successfully created. + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md new file mode 100644 index 0000000000000000000000000000000000000000..88e58e4bea766398e24ae1870c061e0dc385953a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md @@ -0,0 +1,16 @@ +# NotificationActionButton + +The **NotificationActionButton** module describes the button displayed in the notification. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput8+ | [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) | Yes | Yes | User input object. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md new file mode 100644 index 0000000000000000000000000000000000000000..dcd2a4ce8de27431ea343b27bb933d829fcad74c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md @@ -0,0 +1,16 @@ +# NotificationCommonDef + +> **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. + +## BundleOption + +Provides the bundle information of an application. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Mandatory| Description | +| ------ | ------ |---- | ------ | +| bundle | string | Yes| Bundle information of the application.| +| uid | number | No| User ID.| diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md new file mode 100644 index 0000000000000000000000000000000000000000..7c2b3a78da9b2c22c7ae9967552655f6e70a6c8c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md @@ -0,0 +1,77 @@ +# NotificationContent + +The **NotificationContent** module describes the notification content. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](./js-apis-notificationManager.md#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | + +## NotificationBasicContent + +Describes the normal text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| + + +## NotificationLongTextContent + +Describes the long text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | + + +## NotificationMultiLineContent + +Describes the multi-line text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | + + +## NotificationPictureContent + +Describes the picture-attached notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md new file mode 100644 index 0000000000000000000000000000000000000000..f7e1a995b51bcc193e2cd21115eb8e934233eec5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md @@ -0,0 +1,29 @@ +# NotificationFlags + +The **NotificationFlags** module implements a **NotificationFlags** instance. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable vibration for the notification. | + + +## NotificationFlagStatus + +Describes the notification flag status. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | The default flag is used. | +| TYPE_OPEN | 1 | The notification flag is enabled. | +| TYPE_CLOSE | 2 | The notification flag is disabled. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md new file mode 100644 index 0000000000000000000000000000000000000000..205a6c04bdf7fff97c80e44b882fb487712e2c01 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -0,0 +1,63 @@ +# NotificationRequest + +The **NotificationRequest** module describes the notification request. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | Yes | Yes | Notification content. | +| id | number | Yes | Yes | Notification ID. | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | Yes | Yes | Notification slot type. | +| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | +| deliveryTime | number | Yes | Yes | Time when the notification is sent. | +| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | +| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked.| +| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | +| color | number | Yes | Yes | Background color of the notification. Not supported currently.| +| colorEnabled | boolean | Yes | Yes | Whether the notification background color can be enabled. Not supported currently.| +| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | +| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | +| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon in the status bar. | +| label | string | Yes | Yes | Notification label. | +| badgeIconStyle | number | Yes | Yes | Notification badge type. | +| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | Yes | Yes | Buttons in the notification. Up to three buttons are allowed. | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | +| creatorUid8+ | number | Yes | No | UID used for creating the notification. | +| creatorPid | number | Yes | No | PID used for creating the notification. | +| creatorUserId| number | Yes | No | ID of the user who creates the notification. | +| hashCode | string | Yes | No | Unique ID of the notification. | +| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+ | string | Yes | Yes | Notification group name. | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | Yes | Yes | Notification template. | +| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | [DistributedOptions](#distributedoptions) | Yes | Yes | Distributed notification options. | +| deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationflags#notificationFlags) | Yes | No | Notification flags. | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | Yes | Yes | Number of notifications displayed on the application icon. | + + +## DistributedOptions + +Describes distributed notification options. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed8+ | boolean | Yes | Yes | Whether the notification is a distributed notification. | +| supportDisplayDevices8+ | Array\ | Yes | Yes | List of the devices to which the notification can be synchronized. | +| supportOperateDevices8+ | Array\ | Yes | Yes | List of the devices on which the notification can be opened. | +| remindType8+ | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md new file mode 100644 index 0000000000000000000000000000000000000000..8bf9e286d59504be03ff8454d59ce60c31a9a597 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md @@ -0,0 +1,24 @@ +# NotificationSlot + +The **NotificationSlot** module describes the notification slot. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](js-apis-notificationManager.md#slottype) | Yes | Yes | Notification slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value that corresponds to the notification slot type is used.| +| desc | string | Yes | Yes | Notification slot description. | +| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | +| bypassDnd | boolean | Yes | Yes | Whether to bypass DND mode in the system. | +| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | Yes | Yes | Whether to enable vibration for the notification. | +| sound | string | Yes | Yes | Notification alert tone. | +| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | +| lightColor | number | Yes | Yes | Indicator color of the notification. | +| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| enabled9+ | boolean | Yes | No | Whether the notification slot is enabled. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md new file mode 100644 index 0000000000000000000000000000000000000000..557fad664de00eb37567cb2d055c0c0ec2f8d484 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md @@ -0,0 +1,14 @@ +# NotificationTemplate + +The **NotificationTemplate** module describes the notification template. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name| Type | Readable| Writable| Description | +| ---- | ---------------------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Template name.| +| data | {[key:string]: Object} | Yes | Yes | Template data.| diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md new file mode 100644 index 0000000000000000000000000000000000000000..76e673c886d4208354b680501c6ddbb0000e6438 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md @@ -0,0 +1,13 @@ +# NotificationUserInput + +The **NotificationUserInput** module provides the notification user input. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index 37dadd8e2ce6cd3e7c2f33ab05154f20b52cf844..d9d1bb857067e3f9482f564968e8107dc13db010 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -51,7 +51,7 @@ this.context.destroy((err) => { ## InputMethodExtensionContext.destroy -destroy(): Promise; Terminates this ability. This API uses a promise to return the result. @@ -61,13 +61,13 @@ Terminates this ability. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise; | Promise that returns no value.| **Example** ```js this.context.destroy().then(() => { - console.log('Succeed in destroying context.'); + console.log('Succeeded in destroying context.'); }).catch((error) => { console.log('Failed to destroy context: ' + JSON.stringify(error)); }); diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index be7f5edb92e6b7345a69551ce269fa197c524f24..17bdc1697f905a48693041cff2b3a609803675b8 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -884,7 +884,7 @@ inputMethodController.off('selectByRange'); ### on('selectByMovement')10+ -on(type: 'selectByMovement', callback: Callback<Range>): void +on(type: 'selectByMovement', callback: Callback<Movement>): void Enables listening for the selection-by-cursor-movement event. This API uses an asynchronous callback to return the result. @@ -1235,8 +1235,6 @@ showOptionalInputMethods(callback: AsyncCallback<boolean>): void Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) - **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -1275,8 +1273,6 @@ showOptionalInputMethods(): Promise<boolean> Displays a dialog box for selecting an input method. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) - **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index fd98e98d1f748ef094d7dd096033fc0459e8ac8b..c13da820d4fb20828a2b001c54278bfe1cb82c23 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -708,7 +708,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -742,7 +742,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -837,7 +837,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -886,7 +886,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -928,7 +928,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -974,7 +974,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -1013,7 +1013,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -1059,7 +1059,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -1099,7 +1099,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1149,7 +1149,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1192,7 +1192,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1242,7 +1242,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1281,7 +1281,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1326,7 +1326,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1366,7 +1366,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1401,7 +1401,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1435,7 +1435,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1479,7 +1479,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1517,7 +1517,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1562,7 +1562,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1600,7 +1600,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1620,7 +1620,7 @@ try { ### selectByMovement10+ -selectByMovement(range: Range): Promise<void> +selectByMovement(movement: Movement): Promise<void> Selects text based on the specified range. This API uses a promise to return the result. @@ -1645,7 +1645,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **Example** @@ -1682,7 +1682,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -1717,7 +1717,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 5081673fb64f13171a596fd2ed163d4bd8d3c7c9..c39fa3514e9722ba2d33a7dce55378ecb875e3e6 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -175,7 +175,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | -------- | ------------------------------------------------------------ | | 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700101 | The system service is excepted. | **Example** @@ -284,7 +283,7 @@ Defines the parameters that need to be specified for bundle installation, uninst | Name | Type | Mandatory | Description | | ------------------------------ | ------------------------------ | ------------------ | ------------------ | -| userId | number | Yes | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9) to obtain the user of the current process.| +| userId | number | Yes | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user of the current process.| | installFlag | number | Yes | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| | isKeepData | boolean | Yes | Whether to retain the data directory during bundle uninstall.| | hashParams | Array<[HashParam](#hashparam)> | Yes| Hash parameters. | diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index d4f3449adae43eed9b19236aec0d0308feed89e8..22b2225382e82166356b37003483c7c27a1400e0 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,6 +1,6 @@ # @ohos.intl (Internationalization) -The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. + The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. > **NOTE** @@ -48,9 +48,9 @@ Creates a **Locale** object. **Example** ```js // The default constructor uses the current system locale to create a Locale object. - let locale = new Intl.Locale() + let locale = new Intl.Locale(); // Return the current system locale. - let localeID = locale.toString() + let localeID = locale.toString(); ``` @@ -67,13 +67,13 @@ Creates a **Locale** object. | Name | Type | Mandatory | Description | | -------------------- | -------------------------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| -| options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ```js // Create a Locale object named zh-CN. - let locale = new Intl.Locale("zh-CN") - let localeID = locale.toString() // localeID = "zh-CN" + let locale = new Intl.Locale("zh-CN"); + let localeID = locale.toString(); // localeID = "zh-CN" ``` @@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa ``` -## LocaleOptions6+ +## LocaleOptions9+ Represents the locale options. @@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ```js @@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ------------------------------------ | ----------------------------- | -| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ```js @@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object. ``` -## DateTimeOptions6+ +## DateTimeOptions9+ Provides the options for the **DateTimeFormat** object. @@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale. | Name | Type | Mandatory | Description | | -------------------- | -------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ```js @@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | -------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -429,11 +429,11 @@ Obtains the options of the **NumberFormat** object. // Obtain the options of the NumberFormat object. let options = numfmt.resolvedOptions(); let style = options.style; // style = decimal - let notation = options.notation // notation = scientific + let notation = options.notation; // notation = scientific ``` -## NumberOptions6+ +## NumberOptions9+ Defines the device capability. @@ -493,7 +493,7 @@ Creates a **Collator** object. | Name | Type | Mandatory | Description | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ```js @@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ------------------------------------ | ----------------- | -| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** ```js @@ -552,11 +552,11 @@ Returns properties reflecting the locale and collation options of a **Collator** // Obtain the options of the Collator object. let options = collator.resolvedOptions(); let usage = options.usage; // usage = "sort" - let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true + let ignorePunctuation = options.ignorePunctuation; // ignorePunctuation = true ``` -## CollatorOptions8+ +## CollatorOptions9+ Represents the properties of a **Collator** object. @@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ```js @@ -631,7 +631,7 @@ Obtains a string that represents the singular-plural type of the specified numbe | Type | Description | | ------ | ---------------------------------------- | -| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| +| string | Singular-plural type. The value can be any of the following: **zero**, **one**, **two**, **few**, **many**, **others**.| **Example** ```js @@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ``` -## PluralRulesOptions8+ +## PluralRulesOptions9+ Represents the properties of a **PluralRules** object. @@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ```js @@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ``` -## RelativeTimeFormatInputOptions8+ +## RelativeTimeFormatInputOptions9+ Represents the properties of a **RelativeTimeFormat** object. diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index 057e05ac3fd59f22e9bcea5b0fd6064142e95602..123602526ffa59a7af9f20c7ee7eb0775ffae0e6 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -19,7 +19,7 @@ import matrix4 from '@ohos.matrix4' init(array: Array<number>): Matrix4Transit -Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. +Matrix constructor, which is used to create a 4 x 4 matrix by using the input parameter. Column-major order is used. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -33,7 +33,7 @@ Matrix constructor, which is used to create a 4x4 matrix by using the input para | Type | Description | | -------------- | ---------------------------- | -| Matrix4Transit | 4x4 matrix object created based on the input parameter.| +| Matrix4Transit | 4 x 4 matrix object created based on the input parameter.| **array** parameters @@ -458,7 +458,7 @@ struct Test { .width('600px') .height('300px') .margin({ top: 50 }) - Text(`Coordinates before matrix transformation: [${this.transformPoint}]`) + Text(`Coordinates after matrix transformation: [${this.transformPoint}]`) .fontSize(16) .margin({ top: 100 }) Image($r("app.media.image")) diff --git a/en/application-dev/reference/apis/js-apis-measure.md b/en/application-dev/reference/apis/js-apis-measure.md new file mode 100644 index 0000000000000000000000000000000000000000..3e608c26158d219fc76ace69899da778ad6ea576 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-measure.md @@ -0,0 +1,127 @@ +# @ohos.measure (Text Measurement) + +The **measure** module provides APIs for measuring text metrics, such as text height and width. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import measure from '@ohos.measure' +``` + +## measure.measureText + +measureText(options: MeasureOptions): double + +Measures the width of the given single-line text. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [MeasureOptions](#measureoptions) | Yes | Information about the measured text.| + +**Return value** + +| Type | Description | +| ------------ | --------- | +| double | Text width.
The unit is px.| + + +**Example** + +```ts +import measure from '@ohos.measure' +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + @State textWidth : number = measure.measureText({ + textContent: "Hello word", + fontSize: '50px' + }) + build() { + Row() { + Column() { + Text("The width of 'Hello World': " + this.textWidth) + } + .width('100%') + } + .height('100%') + } +} +``` + +## measure.measureTextSize10+ + +measureTextSize(options: MeasureOptions): SizeOptions + +Measures the width of the given single-line text. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [MeasureOptions](#measureoptions) | Yes | Information about the measured text.| + +**Return value** + +| Type | Description | +| ------------ | --------- | +| SizeOptions | Layout width and height occupied by the text.
The unit is px.| + + +**Example** + +```ts +import measure from '@ohos.measure' +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + textSize : SizeOptions = measure.measureTextSize({ + textContent: "Hello word", + fontSize: '50px' + }) + build() { + Row() { + Column() { + Text("The width of 'Hello World': " + this.textSize.width) + Text("The height of 'Hello World': " + this.textSize.height) + } + .width('100%') + } + .height('100%') + } +} +``` + +## MeasureOptions + +Provides attributes of the measured text. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| -------------- | -------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------- | +| textContent | string | Yes | Content of the measured text. | +| constraintWidth10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Layout width of the measured text.
The default unit is vp. | +| fontSize | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Font size of the measured text. If the value is of the number type, the unit fp is used.
Default value: **16fp**
**NOTE**
The value cannot be a percent string. | +| fontStyle | number \| [FontStyle](../arkui-ts/ts-appendix-enums.md#fontstyle) | No | Font style of the measured text.
Default value: **FontStyle.Normal** | +| fontWeight | number \| string \| [FontWeight](../arkui-ts/ts-appendix-enums.md#fontweight) | No | Font width of the measured text. 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 heavier 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](../arkui-ts/ts-types.md#resource) | No | Font family of the measured text. Default value: **'HarmonyOS Sans'**
Only the default font is supported.| +| letterSpacing | number \| string | No | Letter spacing of the measured text.| +| textAlign10+ | number \| [TextAlign](../arkui-ts/ts-appendix-enums.md#textalign) | No | Horizontal alignment mode of the measured text.
Default value: **TextAlign.Start**| +| overflow10+ | number \| [TextOverflow](../arkui-ts/ts-appendix-enums.md#textoverflow) | No | Display mode when the measured text is too long.| +| maxLines10+ | number | No | Maximum number of lines in the measured text.| +| lineHeight10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Line height of the measured text.| +| baselineOffset10+ | number \| string | No | Baseline offset of the measured text.
Default value: **0**| +| textCase10+ | number \| [TextCase](../arkui-ts/ts-appendix-enums.md#textcase) | No | Case of the measured text.
Default value: **TextCase.Normal**| diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 3d29422be8cb7f4c363d3272fa1d00dae4019bc9..a0d85f43ee33d674268067dedf450ac5c300419a 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -357,20 +357,25 @@ For details about the AVPlayer demo, see [AVPlayer Development](../../media/avpl **System capability**: SystemCapability.Multimedia.Media.AVPlayer -| Name | Type | Readable| Writable| Description | -| --------------------------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| -| surfaceId9+ | string | Yes | Yes | Video window ID. By default, there is no video window. It is a static attribute and can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
**Example:**
[Create a surface ID through XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| -| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| -| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| Name | Type | Readable| Writable| Description | +| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| +| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Descriptor of a streaming media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
**Example:**
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained or the live mode is expected, set **fileSize** to **-1**.
2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**.
3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.| +| surfaceId9+ | string | Yes | Yes | Video window ID. By default, there is no video window. It is a static attribute and can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
**Example:**
[Create a surface ID through XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| | audioRendererInfo10+ | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | Yes | Yes | Audio renderer information. The default value of **contentType** is **CONTENT_TYPE_MUSIC**, and the default value of **streamUsage** is **STREAM_USAGE_MEDIA**.
It can be set only when the AVPlayer is in the initialized state.| -| state9+ | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. | -| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.| -| duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live streaming scenarios, **-1** is returned by default.| -| width9+ | number | Yes | No | Video width, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| -| height9+ | number | Yes | No | Video height, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| +| state9+ | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. | +| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.| +| duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live streaming scenarios, **-1** is returned by default.| +| width9+ | number | Yes | No | Video width, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| +| height9+ | number | Yes | No | Video height, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| + +**NOTE** + +After the resource handle (FD) is transferred to the AVPlayer, do not use the resource handle to perform read and write operations, including but not limited to transferring it to multiple AVPlayers. Competition occurs when multiple AVPlayers use the same resource handle to read and write files at the same time, resulting in playback errors. ### on('stateChange')9+ @@ -927,6 +932,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js +printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + avPlayer.getTrackDescription((error, arrList) => { if ((arrList) != null) { for (let i = 0; i < arrList.length; i++) { @@ -964,6 +977,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js let arrayDescription; + +printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} avPlayer.getTrackDescription().then((arrList) => { if (arrList != null) { arrayDescription = arrList; @@ -1060,7 +1081,7 @@ Sets the playback speed. This API can be called only when the AVPlayer is in the **Example** ```js -avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) +avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X) ``` ### on('speedDone')9+ @@ -1553,6 +1574,8 @@ Subscribes to the audio interruption event. When multiple audio and video assets **Example** ```js +import audio from '@ohos.multimedia.audio'; + avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { console.info('audioInterrupt success,and InterruptEvent info is:' + info) }) @@ -1586,7 +1609,7 @@ Enumerates the states of the [AVPlayer](#avplayer9). Your application can proact | Name | Type | Description | | :-----------------------------: | :----: | :----------------------------------------------------------- | -| idle | string | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or **reset()** is called.
In case **createAVPlayer()** is used, all attributes are set to their default values.
In case **reset()** is invoked, the **url9+** or **fdSrc9+** attribute is reset, and other attributes set by the application are retained.| +| idle | string | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or **reset()** is called.
In case **createAVPlayer()** is used, all attributes are set to their default values.
In case **reset()** is called, the **url9+**, **fdSrc9+**, or **dataSrc10+** attribute and the **loop** attribute are reset, and other attributes are retained.| | initialized | string | The AVPlayer enters this state after **url9+** or **fdSrc9+** attribute is set in the idle state. In this case, you can configure static attributes such as the window and audio.| | prepared | string | The AVPlayer enters this state when **prepare()** is called in the initialized state. In this case, the playback engine has prepared the resources.| | playing | string | The AVPlayer enters this state when **play()** is called in the prepared, paused, or completed state.| @@ -1608,6 +1631,18 @@ Describes an audio and video file asset. It is used to specify a particular asse | offset | number | Yes | Resource offset, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.| | length | number | Yes | Resource length, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.| +## AVDataSrcDescriptor10+ + +Defines the descriptor of an audio and video file, which is used in DataSource playback mode.
Use scenario: An application can create a playback instance and start playback before it finishes downloading the audio and video resources. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fileSize | number | Yes | Size of the file to play, in bytes. The value **-1** indicates that the size is unknown. If **fileSize** is set to **-1**, the playback mode is similar to the live mode. In this mode, the **seek** and **setSpeed** operations cannot be performed, and the **loop** attribute cannot be set, indicating that loop playback is unavailable.| +| callback | function | Yes | Callback used to fill in data.
- **buffer**: memory to be filled. The value is of the ArrayBuffer type. This parameter is mandatory.
- **length**: maximum length of the memory to be filled. The value is of the number type. This parameter is mandatory.
- **pos**: position of the data to be filled in the file. The value is of the number type. This parameter is optional. When **fileSize** is set to **-1**, this parameter cannot be used.| + + ## SeekMode8+ Enumerates the video playback seek modes, which can be passed in the **seek** API. @@ -1742,7 +1777,7 @@ let AVRecorderConfig = { location : { latitude : 30, longitude : 130 } } -AVRecorder.prepare(AVRecorderConfig, (err) => { +avRecorder.prepare(AVRecorderConfig, (err) => { if (err == null) { console.info('prepare success'); } else { @@ -1813,7 +1848,7 @@ let AVRecorderConfig = { location : { latitude : 30, longitude : 130 } } -AVRecorder.prepare(AVRecorderConfig).then(() => { +avRecorder.prepare(AVRecorderConfig).then(() => { console.info('prepare success'); }).catch((err) => { console.info('prepare failed and catch error is ' + err.message); @@ -1854,7 +1889,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. -AVRecorder.getInputSurface((err, surfaceId) => { +avRecorder.getInputSurface((err, surfaceId) => { if (err == null) { console.info('getInputSurface success'); surfaceID = surfaceId; @@ -1863,8 +1898,6 @@ AVRecorder.getInputSurface((err, surfaceId) => { } }); -// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); - ``` ### getInputSurface9+ @@ -1900,14 +1933,12 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. -AVRecorder.getInputSurface().then((surfaceId) => { +avRecorder.getInputSurface().then((surfaceId) => { console.info('getInputSurface success'); surfaceID = surfaceId; }).catch((err) => { console.info('getInputSurface failed and catch error is ' + err.message); }); - -// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); ``` ### start9+ @@ -1939,7 +1970,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.start((err) => { +avRecorder.start((err) => { if (err == null) { console.info('start AVRecorder success'); } else { @@ -1977,7 +2008,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.start().then(() => { +avRecorder.start().then(() => { console.info('start AVRecorder success'); }).catch((err) => { console.info('start AVRecorder failed and catch error is ' + err.message); @@ -2013,7 +2044,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.pause((err) => { +avRecorder.pause((err) => { if (err == null) { console.info('pause AVRecorder success'); } else { @@ -2051,7 +2082,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.pause().then(() => { +avRecorder.pause().then(() => { console.info('pause AVRecorder success'); }).catch((err) => { console.info('pause AVRecorder failed and catch error is ' + err.message); @@ -2087,7 +2118,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.resume((err) => { +avRecorder.resume((err) => { if (err == null) { console.info('resume AVRecorder success'); } else { @@ -2125,7 +2156,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.resume().then(() => { +avRecorder.resume().then(() => { console.info('resume AVRecorder success'); }).catch((err) => { console.info('resume AVRecorder failed and catch error is ' + err.message); @@ -2163,7 +2194,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.stop((err) => { +avRecorder.stop((err) => { if (err == null) { console.info('stop AVRecorder success'); } else { @@ -2203,7 +2234,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.stop().then(() => { +avRecorder.stop().then(() => { console.info('stop AVRecorder success'); }).catch((err) => { console.info('stop AVRecorder failed and catch error is ' + err.message); @@ -2238,7 +2269,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.reset((err) => { +avRecorder.reset((err) => { if (err == null) { console.info('reset AVRecorder success'); } else { @@ -2275,7 +2306,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.reset().then(() => { +avRecorder.reset().then(() => { console.info('reset AVRecorder success'); }).catch((err) => { console.info('reset AVRecorder failed and catch error is ' + err.message); @@ -2309,7 +2340,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.release((err) => { +avRecorder.release((err) => { if (err == null) { console.info('release AVRecorder success'); } else { @@ -2345,7 +2376,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.release().then(() => { +avRecorder.release().then(() => { console.info('release AVRecorder success'); }).catch((err) => { console.info('release AVRecorder failed and catch error is ' + err.message); @@ -2370,9 +2401,8 @@ Subscribes to AVRecorder state changes. An application can subscribe to only one **Example** ```js -AVRecorder.on('stateChange', async (state, reason) => { +avRecorder.on('stateChange', async (state, reason) => { console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); - } }); ``` @@ -2393,7 +2423,7 @@ Unsubscribes from AVRecorder state changes. **Example** ```js -AVRecorder.off('stateChange'); +avRecorder.off('stateChange'); ``` ### on('error')9+ @@ -2425,7 +2455,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.on('error', (err) => { +avRecorder.on('error', (err) => { console.info('case avRecorder.on(error) called, errMessage is ' + err.message); }); ``` @@ -2456,7 +2486,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -AVRecorder.off('error'); +avRecorder.off('error'); ``` ## AVRecorderState9+ @@ -2486,7 +2516,7 @@ Describes the audio and video recording parameters. | audioSourceType | [AudioSourceType](#audiosourcetype9) | No | Type of the audio source to record. This parameter is mandatory for audio recording. | | videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. | | profile | [AVRecorderProfile](#avrecorderprofile9) | Yes | Recording profile. This parameter is mandatory. | -| url | string | Yes | Recording output URL: fd://xx (fd number).
![img](figures/en-us_image_url.png)
This parameter is mandatory. | +| url | string | Yes | Recording output URL: fd://xx (fd number).
![img](figures/en-us_image_url.png)
This parameter is mandatory.| | rotation | number | No | Rotation angle of the recorded video. The value can only be 0, 90, 180, or 270. | | location | [Location](#location) | No | Geographical location of the recorded video. | @@ -3759,7 +3789,7 @@ Subscribes to the audio playback events. | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed. | +| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed.| | callback | () => void | Yes | Callback invoked when the event is triggered. | **Example** @@ -4874,7 +4904,7 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resources are released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset. | +| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resources are released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| | callback | ()=>void | Yes | Callback invoked when the event is triggered. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 0ee9b746e29fd8bb0473b664a1acabd0f2f157ae..240108ae1849dfb2fd04d927728c653cdb4627f7 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -2,7 +2,10 @@ > **NOTE** > -> The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +> - This API is deprecated since API version 9 and will be retained until API version 13. +> - Certain functionalities are changed as system APIs and can be used only by system applications. To use these functionalities, call [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md). +> - The functionalities for selecting and storing media assets are still open to common applications. To use these functionalities, call [@ohos.file.picker](js-apis-file-picker.md). ## Modules to Import ```js @@ -34,6 +37,7 @@ This API can be used only in the stage model. **Example (from API version 9)** ```ts +// Obtain a MediaLibrary instance. The instance obtained here is used in later. const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); ``` @@ -92,46 +96,54 @@ Obtains file assets (also called files). This API uses an asynchronous callback **Example** ```js -let fileKeyObj = mediaLibrary.FileKey; -let imageType = mediaLibrary.MediaType.IMAGE; -let imagesFetchOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], -}; -media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { - if (fetchFileResult == undefined) { - console.error('Failed to get fetchFileResult: ' + error); - return; - } - const count = fetchFileResult.getCount(); - if (count < 0) { - console.error('Failed to get count from fetchFileResult: count: ' + count); - return; - } - if (count == 0) { - console.info('The count of fetchFileResult is zero'); - return; - } - - console.info('Get fetchFileResult success, count: ' + count); - fetchFileResult.getFirstObject((err, fileAsset) => { - if (fileAsset == undefined) { - console.error('Failed to get first object: ' + err); +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + // Create options for fetching the files. The options are used to obtain files of the image type. + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + }; + // Obtain the files in asynchronous callback mode. + media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { + // Check whether the result set of the obtained files is undefined. If yes, the API call fails. + if (fetchFileResult == undefined) { + console.error('get fetchFileResult failed with error: ' + error); return; } - console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); - for (let i = 1; i < count; i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (fileAsset == undefined) { - console.error('Failed to get next object: ' + err); - return; - } - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) + // Obtain the total number of files in the result set. + const count = fetchFileResult.getCount(); + // Check whether the number is less than 0. If yes, the API call fails. + if (count < 0) { + console.error('get count from fetchFileResult failed, count: ' + count); + return; } + // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device. + if (count == 0) { + console.info('The count of fetchFileResult is zero'); + return; + } + console.info('Get fetchFileResult successfully, count: ' + count); + // Obtain the first file in the result set in asynchronous callback mode. + fetchFileResult.getFirstObject((error, fileAsset) => { + // Check whether the first file is undefined. If yes, the API call fails. + if (fileAsset == undefined) { + console.error('get first object failed with error: ' + error); + return; + } + console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); + // Call getNextObject to obtain the next file until the last one. + for (let i = 1; i < count; i++) { + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + } + // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called. + fetchFileResult.close(); + }); }); -}); +} ``` + ### getFileAssets7+ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> @@ -157,38 +169,48 @@ Obtains file assets. This API uses a promise to return the result. **Example** ```js -let fileKeyObj = mediaLibrary.FileKey; -let imageType = mediaLibrary.MediaType.IMAGE; -let imagesFetchOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], -}; -media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { - const count = fetchFileResult.getCount(); - if (count < 0) { - console.error('Failed to get count from fetchFileResult: count: ' + count); - return; - } - if (count == 0) { - console.info('The count of fetchFileResult is zero'); - return; - } - console.info('Get fetchFileResult success, count: ' + count); - fetchFileResult.getFirstObject().then(function(fileAsset) { - console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); - for (let i = 1; i < count; i++) { - fetchFileResult.getNextObject().then(function(fileAsset) { - console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); - }).catch(function(err) { - console.error('Failed to get next object: ' + err); - }) +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + // Create options for fetching the files. The options are used to obtain files of the image type. + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + }; + // Obtain the files in promise mode. + media.getFileAssets(imagesFetchOp).then((fetchFileResult) => { + // Obtain the total number of files in the result set. + const count = fetchFileResult.getCount(); + // Check whether the number is less than 0. If yes, the API call fails. + if (count < 0) { + console.error('get count from fetchFileResult failed, count: ' + count); + return; + } + // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device. + if (count == 0) { + console.info('The count of fetchFileResult is zero'); + return; } - }).catch(function(err) { - console.error('Failed to get first object: ' + err); + console.info('Get fetchFileResult successfully, count: ' + count); + // Obtain the first file in the result set in promise mode. + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); + // Call getNextObject to obtain the next file until the last one. + for (let i = 1; i < count; i++) { + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + } + // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called. + fetchFileResult.close(); + }).catch((error) => { + // Calling getFirstObject fails. + console.error('get first object failed with error: ' + error); + }); + }).catch((error) => { + // Calling getFileAssets fails. + console.error('get file assets failed with error: ' + error); }); -}).catch(function(err){ - console.error("Failed to get file assets: " + err); -}); +} ``` ### on8+ @@ -232,7 +254,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb ```js media.off('imageChange', () => { - // stop listening success + // Stop listening successfully. }) ``` @@ -263,11 +285,11 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { + media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => { if (fileAsset != undefined) { console.info('createAsset successfully, message'); } else { - console.error('createAsset failed, message = ' + err); + console.error('createAsset failed with error: ' + error); } }); } @@ -307,8 +329,8 @@ async function example() { const path = await media.getPublicDirectory(DIR_IMAGE); media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); - }).catch((err) => { - console.error('createAsset failed, message = ' + err); + }).catch((error) => { + console.error('createAsset failed with error: ' + error); }); } ``` @@ -349,14 +371,15 @@ async function example() { const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } media.deleteAsset(asset.uri).then(() => { - console.info("deleteAsset successfully"); - }).catch((err) => { - console.error("deleteAsset failed with error:"+ err); + console.info('deleteAsset successfully'); + }).catch((error) => { + console.error('deleteAsset failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -391,16 +414,17 @@ async function example() { const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } - media.deleteAsset(asset.uri, (err) => { - if (err != undefined) { - console.info("deleteAsset successfully"); + media.deleteAsset(asset.uri, (error) => { + if (error != undefined) { + console.error('deleteAsset failed with error: ' + error); } else { - console.error("deleteAsset failed with error:"+ err); + console.info('deleteAsset successfully'); } }); + fetchFileResult.close(); } ``` @@ -423,11 +447,11 @@ Obtains a public directory. This API uses an asynchronous callback to return the ```js let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; -media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { +media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => { if (dicResult == 'Camera/') { - console.info('mediaLibraryTest : getPublicDirectory passed'); + console.info('getPublicDirectory DIR_CAMERA successfully'); } else { - console.error('mediaLibraryTest : getPublicDirectory failed'); + console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error); } }); ``` @@ -457,18 +481,21 @@ Obtains a public directory. This API uses a promise to return the result. ```js async function example() { let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; - const dicResult = await media.getPublicDirectory(DIR_CAMERA); - if (dicResult == 'Camera/') { - console.info('MediaLibraryTest : getPublicDirectory'); - } else { - console.error('MediaLibraryTest : getPublicDirectory failed'); - } + media.getPublicDirectory(DIR_CAMERA).then((dicResult) => { + if (dicResult == 'Camera/') { + console.info('getPublicDirectory DIR_CAMERA successfully'); + } else { + console.error('getPublicDirectory DIR_CAMERA failed'); + } + }).catch((error) => { + console.error('getPublicDirectory failed with error: ' + error); + }); } ``` ### getAlbums7+ -getAlbums(options: MediaFetchOptions, callback: AsyncCallback): void +getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album>>): void Obtains the albums. This API uses an asynchronous callback to return the result. @@ -486,24 +513,24 @@ Obtains the albums. This API uses an asynchronous callback to return the result. **Example** ```js -let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], -}; -media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { - if (albumList != undefined) { - const album = albumList[0]; - console.info('album.albumName = ' + album.albumName); - console.info('album.count = ' + album.count); - } else { - console.error('getAlbum fail, message = ' + err); - } -}) +async function example() { + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { + if (albumList != undefined) { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + } else { + console.error('getAlbums failed with error: ' + error); + } + }) +} ``` ### getAlbums7+ -getAlbums(options: MediaFetchOptions): Promise +getAlbums(options: MediaFetchOptions): Promise<Array<Album>> Obtains the albums. This API uses a promise to return the result. @@ -526,15 +553,17 @@ Obtains the albums. This API uses a promise to return the result. **Example** ```js -let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], -}; -media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ - console.info("getAlbums successfully:"+ JSON.stringify(albumList)); -}).catch(function(err){ - console.error("getAlbums failed with error: " + err); -}); +async function example() { + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + }).catch((error) => { + console.error('getAlbums failed with error: ' + error); + }); +} ``` ### release8+ @@ -550,12 +579,12 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| **Example** ```js -media.release((err) => { +media.release(() => { // do something }); ``` @@ -581,7 +610,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in media.release() ``` -### storeMediaAsset(deprecated) +### storeMediaAsset storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>): void @@ -589,7 +618,7 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t > **NOTE** > -> This API is deprecated since API version 9. +> This API is supported since API version 6 and can be used only by the FA model. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -604,22 +633,22 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t ```js let option = { - src : "/data/storage/el2/base/haps/entry/image.png", - mimeType : "image/*", - relativePath : "Pictures/" + src : '/data/storage/el2/base/haps/entry/image.png', + mimeType : 'image/*', + relativePath : 'Pictures/' }; -mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { - if (err) { - console.error("An error occurred when storing media resources."); +mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => { + if (error) { + console.error('storeMediaAsset failed with error: ' + error); return; } - console.info("Media resources stored. "); + console.info('Media resources stored. '); // Obtain the URI that stores the media asset. }); ``` -### storeMediaAsset(deprecated) +### storeMediaAsset storeMediaAsset(option: MediaAssetOption): Promise<string> @@ -627,7 +656,7 @@ Stores a media asset. This API uses a promise to return the URI that stores the > **NOTE** > -> This API is deprecated since API version 9. +> This API is supported since API version 6 and can be used only by the FA model. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -647,28 +676,28 @@ Stores a media asset. This API uses a promise to return the URI that stores the ```js let option = { - src : "/data/storage/el2/base/haps/entry/image.png", - mimeType : "image/*", - relativePath : "Pictures/" + src : '/data/storage/el2/base/haps/entry/image.png', + mimeType : 'image/*', + relativePath : 'Pictures/' }; mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { - console.info("Media resources stored."); + console.info('Media resources stored.'); // Obtain the URI that stores the media asset. -}).catch((err) => { - console.error("An error occurred when storing media resources."); +}).catch((error) => { + console.error('storeMediaAsset failed with error: ' + error); }); ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): void Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. > **NOTE** -> -> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. +> This API is supported since API version 6 and can be used only by the FA model. +> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -676,7 +705,7 @@ Starts image preview, with the first image to preview specified. This API can be | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.| +| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.| | index | number | Yes | Index of the first image to preview. | | callback | AsyncCallback<void> | Yes | Callback used to return the image preview result. If the preview fails, an error message is returned. | @@ -684,35 +713,35 @@ Starts image preview, with the first image to preview specified. This API can be ```js let images = [ - "datashare:///media/xxxx/2", - "datashare:///media/xxxx/3" + 'datashare:///media/xxxx/2', + 'datashare:///media/xxxx/3' ]; /* Preview online images. let images = [ - "https://media.xxxx.com/image1.jpg", - "https://media.xxxx.com/image2.jpg" + 'https://media.xxxx.com/image1.jpg', + 'https://media.xxxx.com/image2.jpg' ]; */ let index = 1; -mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { - if (err) { - console.error("An error occurred when previewing the images."); +mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => { + if (error) { + console.error('startImagePreview failed with error: ' + error); return; } - console.info("Succeeded in previewing the images."); + console.info('Succeeded in previewing the images.'); }); ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void Starts image preview. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. > **NOTE** -> -> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. +> This API is supported since API version 6 and can be used only by the FA model. +> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -720,41 +749,41 @@ Starts image preview. This API can be used to preview local images whose URIs st | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.| +| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.| | callback | AsyncCallback<void> | Yes | Callback used to return the image preview result. If the preview fails, an error message is returned. | **Example** ```js let images = [ - "datashare:///media/xxxx/2", - "datashare:///media/xxxx/3" + 'datashare:///media/xxxx/2', + 'datashare:///media/xxxx/3' ]; /* Preview online images. let images = [ - "https://media.xxxx.com/image1.jpg", - "https://media.xxxx.com/image2.jpg" + 'https://media.xxxx.com/image1.jpg', + 'https://media.xxxx.com/image2.jpg' ]; */ -mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { - if (err) { - console.error("An error occurred when previewing the images."); +mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => { + if (error) { + console.error('startImagePreview failed with error: ' + error); return; } - console.info("Succeeded in previewing the images."); + console.info('Succeeded in previewing the images.'); }); ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, index?: number): Promise<void> Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses a promise to return the execution result. > **NOTE** -> -> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. +> This API is supported since API version 6 and can be used only by the FA model. +> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -762,7 +791,7 @@ Starts image preview, with the first image to preview specified. This API can be | Name | Type | Mandatory | Description | | ------ | ------------------- | ---- | ---------------------------------------- | -| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.| +| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.| | index | number | No | Index of the first image to preview. If this parameter is not specified, the default value **0** is used. | **Return value** @@ -775,33 +804,33 @@ Starts image preview, with the first image to preview specified. This API can be ```js let images = [ - "datashare:///media/xxxx/2", - "datashare:///media/xxxx/3" + 'datashare:///media/xxxx/2', + 'datashare:///media/xxxx/3' ]; /* Preview online images. let images = [ - "https://media.xxxx.com/image1.jpg", - "https://media.xxxx.com/image2.jpg" + 'https://media.xxxx.com/image1.jpg', + 'https://media.xxxx.com/image2.jpg' ]; */ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { - console.info("Succeeded in previewing the images."); -}).catch((err) => { - console.error("An error occurred when previewing the images."); + console.info('Succeeded in previewing the images.'); +}).catch((error) => { + console.error('startImagePreview failed with error: ' + error); }); ``` -### startMediaSelect(deprecated) +### startMediaSelect startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array<string>>): void Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets. > **NOTE** -> -> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). +> This API is supported since API version 6 and can be used only by the FA model. +> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -809,36 +838,36 @@ Starts media selection. This API uses an asynchronous callback to return the lis | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------------ | -| option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option. | +| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option. | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the list of URIs (starting with **datashare://**) that store the selected media assets.| **Example** ```js let option : mediaLibrary.MediaSelectOption = { - type : "media", + type : 'media', count : 2 }; -mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { - if (err) { - console.error("An error occurred when selecting media resources."); +mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => { + if (error) { + console.error('startMediaSelect failed with error: ' + error); return; } - console.info("Media resources selected."); + console.info('Media resources selected.'); // Obtain the media selection value. }); ``` -### startMediaSelect(deprecated) +### startMediaSelect startMediaSelect(option: MediaSelectOption): Promise<Array<string>> Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets. > **NOTE** -> -> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). +> This API is supported since API version 6 and can be used only by the FA model. +> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -846,7 +875,7 @@ Starts media selection. This API uses a promise to return the list of URIs that | Name | Type | Mandatory | Description | | ------ | --------------------------------------- | ---- | ------- | -| option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option.| +| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option.| **Return value** @@ -858,14 +887,14 @@ Starts media selection. This API uses a promise to return the list of URIs that ```js let option : mediaLibrary.MediaSelectOption = { - type : "media", + type : 'media', count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { - console.info("Media resources selected."); + console.info('Media resources selected.'); // Obtain the media selection value. -}).catch((err) => { - console.error("An error occurred when selecting media resources."); +}).catch((error) => { + console.error('startMediaSelect failed with error: ' + error); }); ``` @@ -893,14 +922,12 @@ Obtains information about online peer devices. This API uses a promise to return async function example() { media.getActivePeers().then((devicesInfo) => { if (devicesInfo != undefined) { - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } + console.info('get distributed info ' + JSON.stringify(devicesInfo)); } else { - console.info('get distributed info is undefined!') + console.info('get distributed info is undefined!'); } - }).catch((err) => { - console.error("get distributed info failed with error:" + err); + }).catch((error) => { + console.error('get distributed info failed with error: ' + error); }); } ``` @@ -927,15 +954,13 @@ Obtains information about online peer devices. This API uses an asynchronous cal ```js async function example() { - media.getActivePeers((err, devicesInfo) => { + media.getActivePeers((error, devicesInfo) => { if (devicesInfo != undefined) { - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } + console.info('get distributed info ' + JSON.stringify(devicesInfo)); } else { - console.error('get distributed fail, message = ' + err) + console.error('get distributed failed with error: ' + error); } - }) + }); } ``` @@ -964,14 +989,12 @@ Obtains information about all peer devices. This API uses a promise to return th async function example() { media.getAllPeers().then((devicesInfo) => { if (devicesInfo != undefined) { - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } + console.info('get distributed info ' + JSON.stringify(devicesInfo)); } else { - console.info('get distributed info is undefined!') + console.info('get distributed info is undefined!'); } - }).catch((err) => { - console.error("get distributed info failed with error: " + err); + }).catch((error) => { + console.error('get distributed info failed with error: ' + error); }); } ``` @@ -998,15 +1021,13 @@ Obtains information about online peer devices. This API uses an asynchronous cal ```js async function example() { - media.getAllPeers((err, devicesInfo) => { + media.getAllPeers((error, devicesInfo) => { if (devicesInfo != undefined) { - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } + console.info('get distributed info ' + JSON.stringify(devicesInfo)); } else { - console.error('get distributed fail, message = ' + err) + console.error('get distributed failed with error: ' + error); } - }) + }); } ``` @@ -1015,7 +1036,6 @@ async function example() { Provides APIs for encapsulating file asset attributes. > **NOTE** -> > 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices. > 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module. @@ -1068,19 +1088,23 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory((err, isDirectory) => { - // do something + asset.isDirectory((error, isDirectory) => { + if (error) { + console.error('isDirectory failed with error: ' + error); + } else { + console.info('isDirectory result:' + isDirectory); + } }); + fetchFileResult.close(); } ``` @@ -1104,21 +1128,21 @@ Checks whether this file asset is a directory. This API uses a promise to return ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory().then(function(isDirectory){ - console.info("isDirectory result:"+ isDirectory); - }).catch(function(err){ - console.error("isDirectory failed with error: " + err); + asset.isDirectory().then((isDirectory) => { + console.info('isDirectory result:' + isDirectory); + }).catch((error) => { + console.error('isDirectory failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1142,20 +1166,20 @@ Commits the modification in this file asset to the database. This API uses an as ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.title = 'newtitle'; asset.commitModify(() => { - console.info('commitModify success'); + console.info('commitModify successfully'); }); + fetchFileResult.close(); } ``` @@ -1179,18 +1203,18 @@ Commits the modification in this file asset to the database. This API uses a pro ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.title = 'newtitle'; - asset.commitModify(); + await asset.commitModify(); + fetchFileResult.close(); } ``` @@ -1200,9 +1224,7 @@ open(mode: string, callback: AsyncCallback<number>): void Opens this file asset. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA @@ -1222,13 +1244,13 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - const asset = await media.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw', (openError, fd) => { - if(fd > 0){ - asset.close(fd); - }else{ - console.error('File Open Failed!' + openError); - } + const asset = await media.createAsset(mediaType, 'image00003.jpg', path); + asset.open('rw', (error, fd) => { + if (fd > 0) { + asset.close(fd); + } else { + console.error('File Open failed with error: ' + error); + } }); } ``` @@ -1239,9 +1261,7 @@ open(mode: string): Promise<number> Opens this file asset. This API uses a promise to return the result. -> **NOTE** -> -> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA @@ -1266,14 +1286,12 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - const asset = await media.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw') - .then((fd) => { - console.info('File fd!' + fd); - }) - .catch((err) => { - console.error('File err!' + err); - }); + const asset = await media.createAsset(mediaType, 'image00003.jpg', path); + asset.open('rw').then((fd) => { + console.info('File open fd: ' + fd); + }).catch((error) => { + console.error('File open failed with error: ' + error); + }); } ``` @@ -1298,30 +1316,28 @@ Closes this file asset. This API uses an asynchronous callback to return the res ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.open('rw').then((fd) => { - console.info('File fd!' + fd); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.error('mediaLibraryTest : close : FAIL ' + closeErr); - console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + console.info('File open fd: ' + fd); + asset.close(fd, (error) => { + if (error) { + console.error('asset.close failed with error: ' + error); } else { - console.info("=======asset.close success====>"); + console.info('asset.close successfully'); } }); - }) - .catch((err) => { - console.error('File err!' + err); + }).catch((error) => { + console.error('File open failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1351,31 +1367,26 @@ Closes this file asset. This API uses a promise to return the result. ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.open('rw').then((fd) => { console.info('File fd!' + fd); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.error('mediaLibraryTest : close : FAIL ' + closeErr); - console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - - } else { - console.info("=======asset.close success====>"); - } + asset.close(fd).then(() => { + console.info('asset.close successfully'); + }).catch((closeErr) => { + console.error('asset.close fail, closeErr: ' + closeErr); }); - }) - .catch((err) => { - console.error('File err!' + err); + }).catch((error) => { + console.error('open File failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1399,19 +1410,23 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); + asset.getThumbnail((error, pixelmap) => { + if (error) { + console.error('mediaLibrary getThumbnail failed with error: ' + error); + } else { + console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap)); + } }); + fetchFileResult.close(); } ``` @@ -1439,17 +1454,21 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); + asset.getThumbnail(size, (error, pixelmap) => { + if (error) { + console.error('mediaLibrary getThumbnail failed with error: ' + error); + } else { + console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap)); + } }); + fetchFileResult.close(); } ``` @@ -1484,19 +1503,17 @@ async function example() { let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + order: fileKeyObj.DATE_ADDED + ' DESC', }; let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size) - .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); - }) - .catch((err) => { - console.error('mediaLibraryTest : getThumbnail fail, err: ' + err); + asset.getThumbnail(size).then((pixelmap) => { + console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap)); + }).catch((error) => { + console.error('mediaLibrary getThumbnail failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1524,16 +1541,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true,function(err){ - // do something + asset.favorite(true,(error) => { + if (error) { + console.error('mediaLibrary favorite failed with error: ' + error); + } else { + console.info('mediaLibrary favorite Successful'); + } }); + fetchFileResult.close(); } ``` @@ -1566,18 +1587,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true).then(function() { - console.info("favorite successfully"); - }).catch(function(err){ - console.error("favorite failed with error: " + err); + asset.favorite(true).then(() => { + console.info('mediaLibrary favorite Successful'); + }).catch((error) => { + console.error('mediaLibrary favorite failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1604,20 +1625,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite((err, isFavorite) => { - if (isFavorite) { - console.info('FileAsset is favorite'); - }else{ - console.info('FileAsset is not favorite'); + asset.isFavorite((error, isFavorite) => { + if (error) { + console.error('mediaLibrary favoriisFavoritete failed with error: ' + error); + } else { + console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite); } }); + fetchFileResult.close(); } ``` @@ -1644,18 +1665,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite().then(function(isFavorite){ - console.info("isFavorite result:"+ isFavorite); - }).catch(function(err){ - console.error("isFavorite failed with error: " + err); + asset.isFavorite().then((isFavorite) => { + console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite); + }).catch((error) => { + console.error('mediaLibrary favoriisFavoritete failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1685,17 +1706,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.trash(true, trashCallBack); - function trashCallBack(err, trash) { - console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); - } + asset.trash(true, (error) => { + if (error) { + console.error('mediaLibrary trash failed with error: ' + error); + } else { + console.info('mediaLibrary trash Successful'); + } + }); + fetchFileResult.close(); } ``` @@ -1730,18 +1754,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.trash(true).then(function() { - console.info("trash successfully"); - }).catch(function(err){ - console.error("trash failed with error: " + err); + asset.trash(true).then(() => { + console.info('trash successfully'); + }).catch((error) => { + console.error('trash failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1768,20 +1792,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isTrash((err, isTrash) => { - if (isTrash == undefined) { - console.error('Failed to get trash state: ' + err); - return; - } - console.info('Get trash state success: ' + isTrash); + asset.isTrash((error, isTrash) => { + if (error) { + console.error('Failed to get trash state failed with error: ' + error); + return; + } + console.info('Get trash state successfully, isTrash result: ' + isTrash); }); + fetchFileResult.close(); } ``` @@ -1808,17 +1832,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isTrash().then(function(isTrash){ - console.info("isTrash result: " + isTrash); - }).catch(function(err){ - console.error("isTrash failed with error: " + err); + asset.isTrash().then((isTrash) => { + console.info('isTrash result: ' + isTrash); + }).catch((error) => { + console.error('isTrash failed with error: ' + error); }); + fetchFileResult.close(); } ``` @@ -1849,11 +1874,12 @@ async function example() { let getFileCountOneOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getFileCountOneOp); const fetchCount = fetchFileResult.getCount(); + console.info('fetchCount result: ' + fetchCount); + fetchFileResult.close(); } ``` @@ -1878,24 +1904,21 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); + console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount); let fileAsset = await fetchFileResult.getFirstObject(); for (var i = 1; i < fetchCount; i++) { - fileAsset = await fetchFileResult.getNextObject(); - if(i == fetchCount - 1) { - console.info('mediaLibraryTest : isLast'); - var result = fetchFileResult.isAfterLast(); - console.info('mediaLibraryTest : isAfterLast:' + result); - console.info('mediaLibraryTest : isAfterLast end'); - fetchFileResult.close(); - } + fileAsset = await fetchFileResult.getNextObject(); + if(i == fetchCount - 1) { + var result = fetchFileResult.isAfterLast(); + console.info('mediaLibrary fileAsset isAfterLast result: ' + result); + fetchFileResult.close(); + } } } ``` @@ -1915,10 +1938,9 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.close(); @@ -1946,18 +1968,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.info('fileAsset.displayName : ' + fileAsset.displayName); + fetchFileResult.getFirstObject((error, fileAsset) => { + if (error) { + console.error('fetchFileResult getFirstObject failed with error: ' + error); + return; + } + console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName); + fetchFileResult.close(); }) } ``` @@ -1983,16 +2005,16 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getFirstObject().then(function(fileAsset){ - console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); - }).catch(function(err){ - console.error("getFirstObject failed with error: " + err); + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); + }).catch((error) => { + console.error('getFirstObject failed with error: ' + error); }); } ``` @@ -2002,6 +2024,9 @@ async function example() { getNextObject(callback: AsyncCallback<FileAsset>): void Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2018,20 +2043,24 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + let fileAsset = await fetchFileResult.getFirstObject(); + if (!fileAsset.isAfterLast) { + fetchFileResult.getNextObject((error, fileAsset) => { + if (error) { + console.error('fetchFileResult getNextObject failed with error: ' + error); + return; + } + console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); + }) + } } + ``` ### getNextObject7+ @@ -2039,6 +2068,9 @@ async function example() { getNextObject(): Promise<FileAsset> Obtains the next file asset in the result set. This API uses a promise to return the result. +> **NOTE** +> +> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2055,15 +2087,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getNextObject(); + let fileAsset = await fetchFileResult.getFirstObject(); + if (!fileAsset.isAfterLast) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); + }).catch((error) => { + console.error('fetchFileResult getNextObject failed with error: ' + error); + }) + } } ``` @@ -2088,18 +2125,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.info('fileAsset.displayName : ' + fileAsset.displayName); + fetchFileResult.getLastObject((error, fileAsset) => { + if (error) { + console.error('getLastObject failed with error: ' + error); + return; + } + console.info('getLastObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }) } ``` @@ -2125,13 +2162,17 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - let lastObject = await fetchFileResult.getLastObject(); + fetchFileResult.getLastObject().then((fileAsset) => { + console.info('getLastObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); + }).catch((error) => { + console.error('getLastObject failed with error: ' + error); + }); } ``` @@ -2147,7 +2188,7 @@ Obtains a file asset with the specified index in the result set. This API uses a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------ | -| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | +| index | number | Yes | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set. | | callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.| **Example** @@ -2157,18 +2198,18 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.info('fileAsset.displayName : ' + fileAsset.displayName); + fetchFileResult.getPositionObject(0, (error, fileAsset) => { + if (error) { + console.error('getPositionObject failed with error: ' + error); + return; + } + console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }) } ``` @@ -2185,7 +2226,7 @@ Obtains a file asset with the specified index in the result set. This API uses a | Name | Type | Mandatory | Description | | ----- | ------ | ---- | -------------- | -| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.| +| index | number | Yes | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set.| **Return value** @@ -2200,16 +2241,16 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.info('fileAsset.displayName : ' + fileAsset.displayName); - }).catch(function (err) { - console.error("getFileAssets failed with error: " + err); + fetchFileResult.getPositionObject(0).then((fileAsset) => { + console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); + }).catch((error) => { + console.error('getPositionObject failed with error: ' + error); }); } ``` @@ -2226,7 +2267,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the file assets.| +| callback | AsyncCallback<Array<[FileAsset](#fileasset7)>> | Yes | Callback used to return the file assets.| **Example** @@ -2235,20 +2276,20 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getAllObject((err, fileAsset) => { - if (err) { - console.error('Failed '); + fetchFileResult.getAllObject((error, fileAssetList) => { + if (error) { + console.error('getAllObject failed with error: ' + error); return; } for (let i = 0; i < fetchFileResult.getCount(); i++) { - console.info('fileAsset.displayName : ' + fileAsset[i].displayName); - } + console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName); + } + fetchFileResult.close(); }) } ``` @@ -2265,7 +2306,7 @@ Obtains all the file assets in the result set. This API uses a promise to return | Type | Description | | ---------------------------------------- | --------------------- | -| Promise> | Promise used to return the file assets.| +| Promise<Array<[FileAsset](#fileasset7)>> | Promise used to return the file assets.| **Example** @@ -2274,13 +2315,19 @@ async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + ' DESC', }; let fetchFileResult = await media.getFileAssets(getImageOp); - var data = fetchFileResult.getAllObject(); + fetchFileResult.getAllObject().then((fileAssetList) => { + for (let i = 0; i < fetchFileResult.getCount(); i++) { + console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName); + } + fetchFileResult.close(); + }).catch((error) => { + console.error('getAllObject failed with error: ' + error); + }); } ``` @@ -2329,12 +2376,12 @@ async function example() { const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.albumName = 'hello'; - album.commitModify((err) => { - if (err) { - console.error('Failed '); - return; - } - console.info('Modify successful.'); + album.commitModify((error) => { + if (error) { + console.error('commitModify failed with error: ' + error); + return; + } + console.info('commitModify successful.'); }) } ``` @@ -2366,10 +2413,10 @@ async function example() { const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.albumName = 'hello'; - album.commitModify().then(function() { - console.info("commitModify successfully"); - }).catch(function(err){ - console.error("commitModify failed with error: " + err); + album.commitModify().then(() => { + console.info('commitModify successfully'); + }).catch((error) => { + console.error('commitModify failed with error: ' + error); }); } ``` @@ -2400,15 +2447,22 @@ async function example() { selectionArgs: [], }; let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], + selections: '', + selectionArgs: [], } + // Obtain the albums that meet the retrieval options and return the album list. const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; - album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack); - function getFileAssetsCallBack(err, fetchFileResult) { - // do something - } + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; + } + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2443,15 +2497,19 @@ async function example() { selectionArgs: [], }; let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], + selections: '', + selectionArgs: [], }; + // Obtain the albums that meet the retrieval options and return the album list. const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; - album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult)); - }).catch(function(err){ - console.error("getFileAssets failed with error: " + err); + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }).catch((error) => { + console.error('album getFileAssets failed with error: ' + error); }); } ``` @@ -2491,32 +2549,31 @@ Enumerates media types. Enumerates key file information. > **NOTE** -> > The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Value | Description | | ------------- | ------------------- | ---------------------------------------------------------- | -| ID | "file_id" | File ID. | -| RELATIVE_PATH | "relative_path" | Relative public directory of the file. | -| DISPLAY_NAME | "display_name" | Display file name. | -| PARENT | "parent" | Parent directory ID. | -| MIME_TYPE | "mime_type" | Extended file attributes. | -| MEDIA_TYPE | "media_type" | Media type. | -| SIZE | "size" | File size, in bytes. | -| DATE_ADDED | "date_added" | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | "date_modified" | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| -| DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | -| TITLE | "title" | Title in the file. | -| ARTIST | "artist" | Artist of the file. | -| AUDIOALBUM | "audio_album" | Audio album. | -| DURATION | "duration" | Duration, in ms. | -| WIDTH | "width" | Image width, in pixels. | -| HEIGHT | "height" | Image height, in pixels. | -| ORIENTATION | "orientation" | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| -| ALBUM_ID | "bucket_id" | ID of the album to which the file belongs. | -| ALBUM_NAME | "bucket_display_name" | Name of the album to which the file belongs. | +| ID | 'file_id' | File ID. | +| RELATIVE_PATH | 'relative_path' | Relative public directory of the file. | +| DISPLAY_NAME | 'display_name' | Display file name. | +| PARENT | 'parent' | Parent directory ID. | +| MIME_TYPE | 'mime_type' | Extended file attributes, such as image/, video/, and file/*. | +| MEDIA_TYPE | 'media_type' | Media type. | +| SIZE | 'size' | File size, in bytes. | +| DATE_ADDED | 'date_added' | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | 'date_modified' | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| +| DATE_TAKEN | 'date_taken' | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | 'title' | Title in the file. | +| ARTIST | 'artist' | Artist of the file. | +| AUDIOALBUM | 'audio_album' | Audio album. | +| DURATION | 'duration' | Duration, in ms. | +| WIDTH | 'width' | Image width, in pixels. | +| HEIGHT | 'height' | Image height, in pixels. | +| ORIENTATION | 'orientation' | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| +| ALBUM_ID | 'bucket_id' | ID of the album to which the file belongs. | +| ALBUM_NAME | 'bucket_display_name' | Name of the album to which the file belongs. | ## DirectoryType8+ @@ -2559,9 +2616,9 @@ Describes options for fetching media files. | Name | Type | Readable| Writable| Description | | ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | +| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| +| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + ' ASC'
Descending: order: mediaLibrary.FileKey.DATE_ADDED + ' DESC'| | uri8+ | string | Yes | Yes | File URI. | | networkId8+ | string | Yes | Yes | Network ID of the registered device. | | extendArgs8+ | string | Yes | Yes | Extended parameters for fetching the files. Currently, no extended parameters are available. | @@ -2577,14 +2634,10 @@ Describes the image size. | width | number | Yes | Yes | Image width, in pixels.| | height | number | Yes | Yes | Image height, in pixels.| -## MediaAssetOption(deprecated) +## MediaAssetOption Implements the media asset option. -> **NOTE** -> -> This API is deprecated since API version 9. - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2594,17 +2647,13 @@ Implements the media asset option. | mimeType | string | Yes | Yes | Multipurpose Internet Mail Extensions (MIME) type of the media.
The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.| | relativePath | string | Yes | Yes | Custom path for storing media assets, for example, 'Pictures/'. If this parameter is unspecified, media assets are stored in the default path.
Default path of images: 'Pictures/'
Default path of videos: 'Videos/'
Default path of audios: 'Audios/'
Default path of files: 'Documents/'| -## MediaSelectOption(deprecated) +## MediaSelectOption Describes media selection option. -> **NOTE** -> -> This API is deprecated since API version 9. - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Readable| Writable| Description | | ----- | ------ | ---- | ---- | -------------------- | | type | 'image' | 'video' | 'media' | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.| -| count | number | Yes | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. | +| count | number | Yes | Yes | Maximum number of media assets that can be selected. The value starts from 1, which indicates that one media asset can be selected. | diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index d5a5f1585a5ae153694833b611861cc49325c4e7..adb1c8ee47ae8dc076f5b2c2f00b2c2ca92a2cd5 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,8 +1,8 @@ # @ohos.net.connection (Network Connection Management) -The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. +The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. -> **NOTE**
+> **NOTE** > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca ```js import connection from '@ohos.net.connection' ``` +## connection.createNetConnection + +createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection + +Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| 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** + +| Type | Description | +| ------------------------------- | -------------------- | +| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| + +**Example** + +```js +// Default network +let netConnection = connection.createNetConnection() + +// Cellular network +let netConnectionCellular = connection.createNetConnection({ + netCapabilities: { + bearerTypes: [connection.NetBearType.BEARER_CELLULAR] + } +}) +``` ## connection.getDefaultNet @@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, err is undefined and data is the default activated data network. Otherwise, err is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.getDefaultNet(function (error, netHandle) { +connection.getDefaultNet(function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(netHandle)) + console.log(JSON.stringify(data)) }) ``` @@ -52,17 +94,25 @@ Obtains the default active data network. This API uses a promise to return the r | --------------------------------- | ------------------------------------- | | Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js -connection.getDefaultNet().then(function (netHandle) { - console.log(JSON.stringify(netHandle)) +connection.getDefaultNet().then(function (data) { + console.log(JSON.stringify(data)) }) ``` ## connection.getDefaultNetSync9+ -getDefaultNetSync(): NetHandle; +getDefaultNetSync(): NetHandle Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. @@ -76,59 +126,321 @@ Obtains the default active data network in synchronous mode. You can use [getNet | --------- | ---------------------------------- | | NetHandle | Handle of the default active data network.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js let netHandle = connection.getDefaultNetSync(); ``` +## connection.getGlobalHttpProxy10+ -## connection.hasDefaultNet +getGlobalHttpProxy(callback: AsyncCallback\): void -hasDefaultNet(callback: AsyncCallback\): void +Obtains the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result. -Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. +**System API**: This is a system API. -**Required permission**: ohos.permission.GET_NETWORK_INFO +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **err** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.getGlobalHttpProxy((error,data) => { + console.info(JSON.stringify(error)); + console.info(JSON.stringify(data)); +}) +``` + +## connection.getGlobalHttpProxy10+ + +getGlobalHttpProxy(): Promise\; + +Obtains the global HTTP proxy configuration of the network. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.getGlobalHttpProxy().then((data) => { + console.info(JSON.stringify(data)); +}).catch(error => { + console.info(JSON.stringify(error)); +}) +``` + +## connection.setGlobalHttpProxy10+ + +setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\): void + +Sets the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.hasDefaultNet(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) +let exclusionStr="192.168,baidu.com" +let exclusionArray = exclusionStr.split(','); +let httpProxy = { + host: "192.168.xx.xxx", + port: 8080, + exclusionList: exclusionArray +} +connection.setGlobalHttpProxy(httpProxy, (error, data) => { + console.info(JSON.stringify(error)); + console.info(JSON.stringify(data)); +}); +``` + +## connection.setGlobalHttpProxy10+ + +setGlobalHttpProxy(httpProxy: HttpProxy): Promise\; + +Sets the global HTTP proxy configuration of the network. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let exclusionStr="192.168,baidu.com" +let exclusionArray = exclusionStr.split(','); +let httpProxy = { + host: "192.168.xx.xxx", + port: 8080, + exclusionList: exclusionArray +} +connection.setGlobalHttpProxy(httpProxy).then((error, data) => { + console.info(JSON.stringify(data)); +}).catch(error=>{ + console.info(JSON.stringify(error)); }) ``` -## connection.hasDefaultNet +## connection.getAppNet9+ -hasDefaultNet(): Promise\ +getAppNet(callback: AsyncCallback\): void -Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. +Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **err** is **undefined** and **data** is the obtained network information. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.getAppNet(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## connection.getAppNet9+ + +getAppNet(): Promise\; + +Obtains information about the network bound to an application. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.NetManager.Core **Return value** -| Type | Description | -| ----------------- | ----------------------------------------------- | -| Promise\ | Promise used to return the result. The value **true** indicates that the default data network is activated.| +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.getAppNet().then((data) => { + console.info(JSON.stringify(data)); +}).catch(error => { + console.info(JSON.stringify(error)); +}) +``` + +## connection.SetAppNet9+ + +setAppNet(netHandle: NetHandle, callback: AsyncCallback\): void + +Binds an application to the specified network, so that the application can access the external network only through this network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.hasDefaultNet().then(function (has) { - console.log('has: ' + has) +connection.getDefaultNet(function (error, netHandle) { + connection.setAppNet(netHandle, (error, data) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); +}) +``` + +## connection.SetAppNet9+ + +setAppNet(netHandle: NetHandle): Promise\; + +Binds an application to the specified network, so that the application can access the external network only through this network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.getDefaultNet().then(function (netHandle) { + connection.setAppNet(netHandle).then((error, data) => { + console.log(JSON.stringify(data)) + }).catch(error => { + console.log(JSON.stringify(error)) + }) }) ``` @@ -136,7 +448,7 @@ connection.hasDefaultNet().then(function (has) { getAllNets(callback: AsyncCallback<Array<NetHandle>>): void -Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. +Obtains the list of all connected networks. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.| +| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **err** is **undefined** and **data** is the list of activated data networks. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.getAllNets(function (error, nets) { +connection.getAllNets(function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(nets)) + console.log(JSON.stringify(data)) }); ``` - ## connection.getAllNets getAllNets(): Promise<Array<NetHandle>> -Obtains the list of all active data networks. This API uses a promise to return the result. +Obtains the list of all connected networks. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return | -------- | -------- | | Promise<Array<[NetHandle](#nethandle)>> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js -connection.getAllNets().then(function (nets) { - console.log(JSON.stringify(nets)) +connection.getAllNets().then(function (data) { + console.log(JSON.stringify(data)) }); ``` @@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) { getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void -Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result. +Obtains connection properties of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network connection information. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle, function (error, info) { + connection.getConnectionProperties(netHandle, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) { getConnectionProperties(netHandle: NetHandle): Promise\ -Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result. +Obtains connection properties of the network corresponding to the **netHandle**. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi | ------------------------------------------------------- | --------------------------------- | | Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getConnectionProperties(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) { getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void -Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result. +Obtains capability information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th | Name | Type | Mandatory| Description | | --------- | --------------------------------------------------- | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network capability information. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle, function (error, info) { + connection.getNetCapabilities(netHandle, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) { getNetCapabilities(netHandle: NetHandle): Promise\ -Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result. +Obtains capability information of the network corresponding to the **netHandle**. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th | --------------------------------------------- | --------------------------------- | | Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getNetCapabilities(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.| -**Example**: +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** ```js -connection.isDefaultNetMetered(function (error, has) { +connection.isDefaultNetMetered(function (error, data) { console.log(JSON.stringify(error)) - console.log('has: ' + has) + console.log('data: ' + data) }) ``` @@ -343,11 +718,216 @@ Checks whether the data traffic usage on the current network is metered. This AP | ----------------- | ----------------------------------------------- | | Promise\ | Promise used to return the result. The value **true** indicates the data traffic usage is metered.| -**Example**: +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.isDefaultNetMetered().then(function (data) { + console.log('data: ' + data) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(callback: AsyncCallback\): void + +Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates the default data network is activated.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.hasDefaultNet(function (error, data) { + console.log(JSON.stringify(error)) + console.log('data: ' + data) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(): Promise\ + +Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** indicates that the default data network is activated.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** ```js -connection.isDefaultNetMetered().then(function (has) { - console.log('has: ' + has) +connection.hasDefaultNet().then(function (data) { + console.log('data: ' + data) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(callback: AsyncCallback\): void + +Enables the airplane mode. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.enableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(): Promise\ + +Enables the airplane mode. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.enableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.disableAirplaneMode + +disableAirplaneMode(callback: AsyncCallback\): void + +Disables the airplane mode. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.disableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.disableAirplaneMode + +disableAirplaneMode(): Promise\ + +Disables the airplane mode. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +connection.disableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) }) ``` @@ -355,9 +935,8 @@ connection.isDefaultNetMetered().then(function (has) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports connection of the data network. This API uses an asynchronous callback to return the result. - -If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. +This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -368,7 +947,17 @@ If this API is called, the application considers that the network connection sta | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** @@ -384,9 +973,8 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -Reports connection of the data network. This API uses a promise to return the result. - -If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. +This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -399,11 +987,20 @@ If this API is called, the application considers that the network connection sta | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| **Return value** - | Type| Description| | -------- | -------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js @@ -414,14 +1011,12 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetDisconnected reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports disconnection of the data network. This API uses an asynchronous callback to return the result. - -If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. +This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -432,7 +1027,17 @@ If this API is called, the application considers that the network connection sta | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** @@ -444,14 +1049,12 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetDisconnected reportNetDisconnected(netHandle: NetHandle): Promise<void> -Reports disconnection of the data network. This API uses a promise to return the result. - -If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. +This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -464,11 +1067,20 @@ If this API is called, the application considers that the network connection sta | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| **Return value** - | Type| Description| | -------- | -------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js @@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | - -**Example** - -```js -let host = "xxxx"; -connection.getAddressesByName(host, function (error, addresses) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(addresses)) -}) -``` - -## connection.getAddressesByName - -getAddressesByName(host: string): Promise\> - -Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result. - -**Required permission**: ohos.permission.GET_NETWORK_INFO - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| - -**Return value** - -| Type | Description | -| ------------------------------------------- | ----------------------------- | -| Promise\> | Promise used to return the result.| - -**Example** - -```js -let host = "xxxx"; -connection.getAddressesByName(host).then(function (addresses) { - console.log(JSON.stringify(addresses)) -}) -``` - -## connection.enableAirplaneMode - -enableAirplaneMode(callback: AsyncCallback\): void - -Enables the airplane mode. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.enableAirplaneMode(function (error) { +let host = "xxxx"; +connection.getAddressesByName(host, function (error, data) { console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` -## connection.enableAirplaneMode +## connection.getAddressesByName -enableAirplaneMode(): Promise\ +getAddressesByName(host: string): Promise\> -Enables the airplane mode. This API uses a promise to return the result. +Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result. -**System API**: This is a system API. +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core -**System capability**: SystemCapability.Communication.NetManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| host | string | Yes | Host name to resolve.| **Return value** | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise that returns no value.| +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js -connection.enableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) +let host = "xxxx"; +connection.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) ``` -## connection.disableAirplaneMode - -disableAirplaneMode(callback: AsyncCallback\): void - -Disables the airplane mode. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.NetManager.Core +## NetConnection -**Parameters** +Represents the network connection handle. -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +### register -**Example** +register(callback: AsyncCallback\): void -```js -connection.disableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) -}) -``` +Registers a listener for network status changes. -## connection.disableAirplaneMode +**Required permission**: ohos.permission.GET_NETWORK_INFO -disableAirplaneMode(): Promise\ +**System capability**: SystemCapability.Communication.NetManager.Core -Disables the airplane mode. This API uses a promise to return the result. +**Parameters** -**System API**: This is a system API. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **err** is **undefined**. Otherwise, **err** is an error object.| -**System capability**: SystemCapability.Communication.NetManager.Core +**Error codes** -**Return value** +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | +| 2101008 | The callback is not exists. | +| 2101022 | The number of requests exceeded the maximum. | -| Type | Description | -| ------------------------------------------- | ----------------------------- | -| Promise\ | Promise that returns no value.| **Example** ```js -connection.disableAirplaneMode().then(function (error) { +netConnection.register(function (error) { console.log(JSON.stringify(error)) }) ``` -## connection.createNetConnection +### unregister -createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection +unregister(callback: AsyncCallback\): void -Obtains the handle of the network specified by **netSpecifier**. +Unregisters the listener for network status changes. **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| 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.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **err** is **undefined**. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| ------------------------------- | -------------------- | -| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | +| 2101007 | The same callback exists. | **Example** ```js -// Default network -let netConnection = connection.createNetConnection() - -// Cellular network -let netConnectionCellular = connection.createNetConnection({ - netCapabilities: { - bearerTypes: [connection.NetBearType.BEARER_CELLULAR] - } +netConnection.unregister(function (error) { + console.log(JSON.stringify(error)) }) ``` -## NetConnection - -Represents the network connection handle. - ### on('netAvailable') on(type: 'netAvailable', callback: Callback\): void Registers a listener for **netAvailable** events. +**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netAvailable**.
**netAvailable**: event indicating that the data network is available.| -| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netAvailable**.
**netAvailable**: event indicating that the data network is available.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.| **Example** ```js -netConnection.on('netAvailable', function (data) { +// Create a NetConnection object. +let netCon = connection.createNetConnection() + +// Call register to register a listener. +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// Subscribe to netAvailable events. Event notifications can be received only after register is called. +netCon.on('netAvailable', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netCapabilitiesChange') +### on('netBlockStatusChange') -on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void +on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void -Registers a listener for **netCapabilitiesChange** events. +Registers a listener for **netBlockStatusChange** events. + +**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. **System capability**: SystemCapability.Communication.NetManager.Core @@ -707,22 +1291,38 @@ Registers a listener for **netCapabilitiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that network capabilities have changed.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).| **Example** ```js -netConnection.on('netCapabilitiesChange', function (data) { +// Create a NetConnection object. +let netCon = connection.createNetConnection() + +// Call register to register a listener. +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// Subscribe to netBlockStatusChange events. Event notifications can be received only after register is called. +netCon.on('netBlockStatusChange', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netConnectionPropertiesChange') +### on('netCapabilitiesChange') -on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void +on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void -Registers a listener for **netConnectionPropertiesChange** events. +Registers a listener for **netCapabilitiesChange** events. + +**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. **System capability**: SystemCapability.Communication.NetManager.Core @@ -730,22 +1330,38 @@ Registers a listener for **netConnectionPropertiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that the network capabilities have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| **Example** ```js -netConnection.on('netConnectionPropertiesChange', function (data) { +// Create a NetConnection object. +let netCon = connection.createNetConnection() + +// Call register to register a listener. +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// Subscribe to netCapabilitiesChange events. Event notifications can be received only after register is called. +netCon.on('netCapabilitiesChange', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netBlockStatusChange') +### on('netConnectionPropertiesChange') -on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void +on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void -Registers a listener for **netBlockStatusChange** events. +Registers a listener for **netConnectionPropertiesChange** events. + +**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. **System capability**: SystemCapability.Communication.NetManager.Core @@ -753,15 +1369,29 @@ Registers a listener for **netBlockStatusChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| **Example** ```js -netConnection.on('netBlockStatusChange', function (data) { +// Create a NetConnection object. +let netCon = connection.createNetConnection() + +// Call register to register a listener. +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// Subscribe to netConnectionPropertiesChange events. Event notifications can be received only after register is called. +netCon.on('netConnectionPropertiesChange', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netLost') @@ -770,22 +1400,37 @@ on(type: 'netLost', callback: Callback\): void Registers a listener for **netLost** events. +**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| -| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).| **Example** ```js -let netConnection1 = connection.createNetConnection() -netConnection1.on('netLost', function (data) { +// Create a NetConnection object. +let netCon = connection.createNetConnection() + +// Call register to register a listener. +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// Subscribe to netLost events. Event notifications can be received only after register is called. +netCon.on('netLost', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netUnavailable') @@ -794,65 +1439,35 @@ on(type: 'netUnavailable', callback: Callback\): void Registers a listener for **netUnavailable** events. +**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| -| callback | Callback\ | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| +| callback | Callback\ | Yes | Callback used to return the result, which is empty.| **Example** ```js -netConnection.on('netUnavailable', function (data) { - console.log(JSON.stringify(data)) -}) -``` - -### register - -register(callback: AsyncCallback\): void - -Registers a listener for network status changes. - -**Required permission**: ohos.permission.GET_NETWORK_INFO - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +// Create a NetConnection object. +let netCon = connection.createNetConnection() -**Example** - -```js -netConnection.register(function (error) { +// Call register to register a listener. +netCon.register(function (error) { console.log(JSON.stringify(error)) }) -``` - -### unregister - -unregister(callback: AsyncCallback\): void - -Unregisters the listener for network status changes. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example** +// Subscribe to netUnavailable events. Event notifications can be received only after register is called. +netCon.on('netUnavailable', function (data) { + console.log(JSON.stringify(data)) +}) -```js -netConnection.unregister(function (error) { +// Call unregister to unregister the listener. +netCon.unregister(function (error) { console.log(JSON.stringify(error)) }) ``` @@ -861,24 +1476,22 @@ netConnection.unregister(function (error) { Defines the handle of the data network. -Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object. +Before invoking **NetHandle** APIs, call **getNetHandle** to obtain a **NetHandle** object. **System capability**: SystemCapability.Communication.NetManager.Core -### Parameters +### Attributes -| Name| Type | Description | -| ------ | ------ | ------------------------- | -| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| +| Name | Type | Mandatory| Description | +| ------ | ------ | --- |------------------------- | +| netId | number | Yes | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| ### bindSocket9+ -bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; +bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO - **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses | Name | Type | Mandatory| Description | | ----------- | ------------------------ | ---- | -------------------------------| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js import socket from "@ohos.net.socket"; -connection.getDefaultNet().then((netHandle)=>{ +connection.getDefaultNet().then((netHandle) => { var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } - netHandle.bindSocket(tcp, (error, data)=>{ + netHandle.bindSocket(tcp, (error, data) => { if (error) { console.log(JSON.stringify(error)); } else { @@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{ }) } else { let callback = value => { - console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } udp.on('message', callback); udp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } udp.on('message', (data) => { console.log(JSON.stringify(data)) }); - netHandle.bindSocket(udp,(error, data)=>{ + netHandle.bindSocket(udp, (error, data) => { if (error) { console.log(JSON.stringify(error)); } else { @@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{ }) ``` -### bindSocket +### bindSocket9+ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO - **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses | -------------- | ---------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js import socket from "@ohos.net.socket"; -connection.getDefaultNet().then((netHandle)=>{ +connection.getDefaultNet().then((netHandle) => { var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } - netHandle.bindSocket(tcp).then((err, data) => { - if (err) { - console.log(JSON.stringify(err)); - } else { - console.log(JSON.stringify(data)); - } + netHandle.bindSocket(tcp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); }) }) } else { let callback = value => { - console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } udp.on('message', callback); udp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } udp.on('message', (data) => { console.log(JSON.stringify(data)); }) - netHandle.bindSocket(udp).then((err, data) => { - if (err) { - console.log(JSON.stringify(err)); - } else { - console.log(JSON.stringify(data)); - } + netHandle.bindSocket(udp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); }) }) } }) ``` - ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void @@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host, function (error, addresses) { + netHandle.getAddressesByName(host, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(addresses)) + console.log(JSON.stringify(data)) }) }) ``` @@ -1052,7 +1686,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| +| host | string | Yes | Host name to resolve.| **Return value** @@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre | ------------------------------------------- | ----------------------------- | | Promise\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host).then(function (addresses) { - console.log(JSON.stringify(addresses)) + netHandle.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **err** is **undefined**, and **data** is the first obtained IP address. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **Example** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressByName(host, function (error, address) { + netHandle.getAddressByName(host, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(address)) + console.log(JSON.stringify(data)) }) }) ``` @@ -1114,7 +1768,7 @@ Resolves the host name by using the corresponding network to obtain the first IP | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| +| host | string | Yes | Host name to resolve.| **Return value** @@ -1122,66 +1776,88 @@ Resolves the host name by using the corresponding network to obtain the first IP | ----------------------------------- | ------------------------------- | | Promise\<[NetAddress](#netaddress)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressByName(host).then(function (address) { - console.log(JSON.stringify(address)) + netHandle.getAddressByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` -## NetSpecifier +## NetCap -Provides an instance that bears data network capabilities. +Defines the network capability. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | -| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| +| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| +| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.| +| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).| +| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the connection management module.| -## NetCapabilities +## NetBearType -Defines the network capability set. +Enumerates network types. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.| -| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.| -| networkCap | Array<[NetCap](#netcap)> | No | Network capability. | -| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. | +| Name | Value | Description | +| --------------- | ---- | ----------- | +| BEARER_CELLULAR | 0 | Cellular network. | +| BEARER_WIFI | 1 | Wi-Fi network.| +| BEARER_ETHERNET | 3 | Ethernet network.| -## NetCap +## HttpProxy10+ -Defines the network capability. +Defines the global HTTP proxy configuration of the network. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Value | Description | -| ------------------------ | ---- | ---------------------- | -| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| -| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| -| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| -| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| -| NET_CAPABILITY_VALIDATED | 16 | The network is available. | +| Name | Type | Mandatory| Description | +| ------ | ------ | --- |------------------------- | +| host | string | No | Host name of the proxy server.| +| port | number | No | Host port.| +| exclusionList | Array | No | List of hosts that do not use the proxy server.| -## NetBearType +## NetSpecifier -Defines the network type. +Provides an instance that bears data network capabilities. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Value | Description | -| --------------- | ---- | ----------- | -| BEARER_CELLULAR | 0 | Cellular network | -| BEARER_WIFI | 1 | Wi-Fi network| -| BEARER_ETHERNET | 3 | Ethernet network| +| Name | Type | Mandatory | Description | +| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | +| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| + +## NetCapabilities + +Defines the network capability set. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| --------------------- | ---------------------------------- | --- | ------------------------ | +| linkUpBandwidthKbps | number | No| Uplink (from the device to the network) bandwidth. | +| linkDownBandwidthKbps | number | No| Downlink (from the network to the device) bandwidth. | +| networkCap | Array\<[NetCap](#netcap)> | No| Network capability. | +| bearerTypes | Array\<[NetBearType](#netbeartype)> | Yes| Network type. | ## ConnectionProperties @@ -1189,48 +1865,48 @@ Defines the network connection properties. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| interfaceName | string | Yes | NIC card name. | -| domains | string | Yes | Domain. The default value is **""**.| -| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | -| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | -| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| -| mtu | number | Yes | Maximum transmission unit (MTU). | +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ----|---------------- | +| interfaceName | string | Yes|Network interface card (NIC) name. | +| domains | string | Yes|Domain. The default value is **""**.| +| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Link information. | +| routes | Array\<[RouteInfo](#routeinfo)> | Yes|Route information. | +| dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).| +| mtu | number | Yes|Maximum transmission unit (MTU). | -## LinkAddress +## RouteInfo -Network link information. +Defines network route information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| address | [NetAddress](#netaddress) | Yes | Link address. | -| prefixLength | number | Yes | Length of the link address prefix.| +| Name | Type | Mandatory|Description | +| -------------- | --------------------------- | --- |---------------- | +| interface | string | Yes|NIC name. | +| destination | [LinkAddress](#linkaddress) | Yes|Destination address. | +| gateway | [NetAddress](#netaddress) | Yes|Gateway address. | +| hasGateway | boolean | Yes|Whether a gateway is present. | +| isDefaultRoute | boolean | Yes|Whether the route is the default route.| -## RouteInfo +## LinkAddress -Network route information. +Defines network link information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| interface | string | Yes | NIC card name. | -| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. | -| gateway | [NetAddress](#netaddress) | Yes | Gateway address. | -| hasGateway | boolean | Yes | Whether a gateway is present. | -| isDefaultRoute | boolean | Yes | Whether the route is the default route.| +| Name | Type | Mandatory|Description | +| ------------ | ----------------------- |---- |-------------------- | +| address | [NetAddress](#netaddress) | Yes| Link address. | +| prefixLength | number | Yes|Length of the link address prefix.| ## NetAddress -Defines the network address. +Defines a network address. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| address | string | Yes | Network address. | -| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | No | Port number. The value ranges from **0** to **65535**. | +| Name | Type | Mandatory| Description | +| ------- | ------ | -- |------------------------------ | +| address | string | Yes|Network address. | +| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| +| port | number | No|Port number. The value ranges from **0** to **65535**. | diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index d41845ec1859507bb96a071dff2a57e16f4cf12b..3445952a9c818fad947373508accb50322e8cf59 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,8 +1,8 @@ -# @ohos.net.ethernet (Ethernet Connection Management) +# # @ohos.net.ethernet (Ethernet Connection Management) The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. -> **NOTE**
+> **NOTE** > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -17,30 +17,51 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac Sets the network interface configuration. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------------ | -| iface | string | Yes | Name of the network interface. | +| iface | string | Yes | Interface name. | | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | + **Example** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, - (error) => { - if (error) { - console.log("setIfaceConfig callback error = " + error); - } else { - console.log("setIfaceConfig callback ok "); - } - }); +ethernet.setIfaceConfig("eth0", { + mode: 0, + ipAddr: "192.168.xx.xxx", + route: "192.168.xx.xxx", + gateway: "192.168.xx.xxx", + netMask: "255.255.255.0", + dnsServers: "1.1.1.1", + domain: "2.2.2.2" +}, (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + JSON.stringify(error)); + } else { + console.log("setIfaceConfig callback ok "); + } +}); ``` ## ethernet.setIfaceConfig @@ -49,31 +70,53 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ Sets the network interface configuration. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------- | ---- | ------------------------ | -| iface | string | Yes | Name of the network interface. | +| iface | string | Yes | Interface name. | | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| **Return value** | Type | Description | | ------------------- | ----------------------------------------------------------- | -| Promise\ | Promise that returns no value.| +| Promise\ | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | **Example** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { +ethernet.setIfaceConfig("eth0", { + mode: 0, + ipAddr: "192.168.xx.xxx", + route: "192.168.xx.xxx", + gateway: "192.168.xx.xxx", + netMask: "255.255.255.0", + dnsServers: "1.1.1.1", + domain: "2.2.2.2" +}).then(() => { console.log("setIfaceConfig promiss ok "); -}).catch((error) => { - console.log("setIfaceConfig promiss error = " + error); +}).catch(error => { + console.log("setIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` @@ -83,31 +126,44 @@ getIfaceConfig(iface: string, callback: AsyncCallback\): Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory | Description | | -------- | ----------------------------------------------- | ----- | ------------ | -| iface | string | Yes | Name of the network interface.| -| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | +| iface | string | Yes | Interface name.| +| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | **Example** ```js ethernet.getIfaceConfig("eth0", (error, value) => { if (error) { - console.log("getIfaceConfig callback error = " + error); + console.log("getIfaceConfig callback error = " + JSON.stringify(error)); } else { - console.log("getIfaceConfig callback mode = " + value.mode); - console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); - console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); - console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); - console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); - console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); - console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); + console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); + console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); + console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); + console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); + console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); + console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); } }); ``` @@ -118,64 +174,90 @@ getIfaceConfig(iface: string): Promise\ Obtains the configuration of a network interface. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------ | -| iface | string | Yes | Name of the network interface.| +| iface | string | Yes | Interface name.| **Return value** | Type | Description | | --------------------------------- | ---------------------------------- | -| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | +| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | **Example** ```js ethernet.getIfaceConfig("eth0").then((data) => { - console.log("getIfaceConfig promiss mode = " + data.mode); - console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); - console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); - console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); - console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); - console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); - console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); -}).catch((error) => { - console.log("getIfaceConfig promiss error = " + error); + console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode)); + console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr)); + console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route)); + console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway)); + console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask)); + console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers)); + console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain)); +}).catch(error => { + console.log("getIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` ## ethernet.isIfaceActive -isIfaceActive(iface?: string, callback: AsyncCallback\): void +isIfaceActive(iface: string, callback: AsyncCallback\): void Checks whether a network interface is active. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------------------------- | -| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface. | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **Example** ```js ethernet.isIfaceActive("eth0", (error, value) => { - if (error) { - console.log("whether2Activate callback error = " + error); - } else { - console.log("whether2Activate callback = " + value); - } + if (error) { + console.log("whether2Activate callback error = " + JSON.stringify(error)); + } else { + console.log("whether2Activate callback = " + JSON.stringify(value)); + } }); ``` @@ -185,15 +267,17 @@ isIfaceActive(iface: string): Promise\ Checks whether a network interface is active. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| +| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface.| **Return value** @@ -201,13 +285,24 @@ Checks whether a network interface is active. This API uses a promise to return | ----------------| ------------------------------------------------------------------ | | Promise\ | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **Example** ```js ethernet.isIfaceActive("eth0").then((data) => { - console.log("isIfaceActive promiss = " + data); -}).catch((error) => { - console.log("isIfaceActive promiss error = " + error); + console.log("isIfaceActive promiss = " + JSON.stringify(data)); +}).catch(error => { + console.log("isIfaceActive promiss error = " + JSON.stringify(error)); }); ``` @@ -215,30 +310,40 @@ ethernet.isIfaceActive("eth0").then((data) => { getAllActiveIfaces(callback: AsyncCallback\>): void -Obtains all active network interfaces. This API uses an asynchronous callback to return the result. +Obtains the list of all active network interfaces. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | **Example** ```js ethernet.getAllActiveIfaces((error, value) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + error); - } else { - console.log("getAllActiveIfaces callback value.length = " + value.length); - for (let i = 0; i < value.length; i++) { - console.log("getAllActiveIfaces callback = " + value[i]); + if (error) { + console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); + } else { + console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); + } } - } }); ``` @@ -246,30 +351,38 @@ ethernet.getAllActiveIfaces((error, value) => { getAllActiveIfaces(): Promise\> -Obtains all active network interfaces. This API uses a promise to return the result. +Obtains the list of all active network interfaces. This API uses a promise to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO +**System API**: This is a system API. -**System capability**: SystemCapability.Communication.NetManager.Core +**Required permission**: ohos.permission.GET_NETWORK_INFO -**Parameters** +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Return value** | Type | Description | | ------------------------------ | ----------------------------------------------- | -| Promise\> | Promise used to return all the active network interface names obtained.| +| Promise\> | Promise used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | **Example** ```js ethernet.getAllActiveIfaces().then((data) => { - console.log("getAllActiveIfaces promiss data.length = " + data.length); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces promiss = " + data[i]); - } -}).catch((error) => { - console.log("getAllActiveIfaces promiss error = " + error); + console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length)); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i])); + } +}).catch(error => { + console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error)); }); ``` @@ -277,22 +390,26 @@ ethernet.getAllActiveIfaces().then((data) => { Defines the network configuration for the Ethernet connection. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| -| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| -| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| +**System capability**: SystemCapability.Communication.NetManager.Ethernet + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------- | ---|------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.| +| ipAddr | string | Yes| Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Yes| Route of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| ## IPSetMode Defines the configuration mode of the Ethernet connection. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Ethernet | Name | Value | Description | | ------------------------ | ---- | ---------------------- | diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..375ee31e24b9a24d14aae0217f12b8cd78eb57b1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1558 @@ +# @ohos.net.policy (Network Policy Management) + +The **policy** module provides APIs for managing network policies, through which you can control and manage the data volume used. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +Sets a background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +Sets a background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(callback: AsyncCallback\): void + +Obtains the background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.isBackgroundAllowed((error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(): Promise\; + +Obtains the background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.isBackgroundAllowed().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void + +Sets an application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +Sets an application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void + +Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +Obtains an application-specific network policy by **uid**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void + +Obtains the network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getNetQuotaPolicies((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +Obtains the network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getNetQuotaPolicies().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void + +Sets an array of network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +Sets an array of network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then(function(error, data){ + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void + +Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +Checks whether an application is allowed to access metered networks. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void + +Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +Checks whether an application is allowed to access the given network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getDeviceIdleAllowList + +getDeviceIdleAllowList(callback: AsyncCallback\>): void + +Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getDeviceIdleAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getDeviceIdleAllowList + +getDeviceIdleAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getDeviceIdleAllowList().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void + +Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +Obtains the background network policies configured for the given application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { + +}) +this.firstParam = iccid +policy.resetPolicies(this.firstParam).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void + +Updates a reminder policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +Updates a reminder policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +Sets whether to add an application to the power-saving allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the power-saving allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPowerSaveAllowList + +getPowerSaveAllowList(callback: AsyncCallback\>): void + +Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPowerSaveAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPowerSaveAllowList + +getPowerSaveAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPowerSaveAllowList().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.on + +Functions as the handle to a network policy. + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void + +Subscribes to policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.| +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result. It is called when the registered network policy changes.| + +**Example** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void + +Subscribes to rule changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.| +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result. It is called when the registered rule changes.| + +**Example** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void + +Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered **iface** change event.| +| callback | Callback\> | Yes | Callback used to return the result. It is called when the registered metered **iface** changes.| + +**Example** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void + +Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.| +| callback | Callback\> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.| + +**Example** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void + +Subscribes to background network policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.| +| callback | Callback\ | Yes | Callback used to return the result. It is called when the registered background network policy changes.| + +**Example** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +Enumerates the background network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.| +| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.| +| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.| +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the allowlist are allowed to access metered networks when they are running in the background.| + +## NetQuotaPolicy + +Defines a network quota policy. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.| +| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.| +| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.| +| periodDuration | string | Start time of metering.| +| warningBytes | number | Data volume threshold for generating an alarm.| +| limitBytes | number | Data volume quota.| +| lastWarningRemind | string | Last time when an alarm was generated.| +| lastLimitRemind | string | Last time when the quota was exhausted.| +| metered | string | Whether the network is a metered network.| +| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.| + +## LimitAction + +Enumerates the actions that can be taken when the data volume quota is reached. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | Default policy.| +| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.| +| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.| + +## NetUidRule + +Enumerates the metered network rules. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | Default rule.| +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.| +| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.| +| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.| +| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).| +| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).| + +## RemindType + +Enumerates the reminder types. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| + +## NetUidPolicy + +Enumerates the application-specific network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | Default network policy.| +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.| +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.| diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 144ffa9c6e2d405c83e7cf14fdb7278c616759d3..f4682131182b59d9b54c26978ec780cd738172ef 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,8 +1,9 @@ -# @ohos.net.sharing (Network Sharing) +# # @ohos.net.sharing (Network Sharing) The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js @@ -56,6 +66,15 @@ Checks whether network sharing is supported. This API uses a promise to return t | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js @@ -84,6 +103,14 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -99,10 +126,10 @@ isSharing(): Promise\ Checks whether network sharing is in progress. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL - **System API**: This is a system API. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -111,6 +138,14 @@ Checks whether network sharing is in progress. This API uses a promise to return | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -127,10 +162,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL - **System API**: This is a system API. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { +let SHARING_WIFI=0; +sharing.startSharing(SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -173,11 +224,27 @@ Starts network sharing of a specified type. This API uses a promise to return th | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { +let SHARING_WIFI=0; +sharing.startSharing(SHARING_WIFI).then(() => { console.log("start wifi sharing successful"); }).catch(error => { console.log("start wifi sharing failed"); @@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { +let SHARING_WIFI=0; +sharing.stopSharing(SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -236,11 +317,25 @@ Stops network sharing of a specified type. This API uses a promise to return the | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { +let SHARING_WIFI=0; +sharing.stopSharing(SHARING_WIFI).then(() => { console.log("stop wifi sharing successful"); }).catch(error => { console.log("stop wifi sharing failed"); @@ -265,6 +360,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -292,6 +395,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -320,6 +431,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -347,6 +466,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -375,6 +502,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -402,6 +537,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -428,14 +571,25 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| | callback | AsyncCallback\> | Yes | Callback used to return an array of NIC names.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js -import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { +import SharingIfaceState from '@ohos.net.sharing' +let SHARING_BLUETOOTH=2; +sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -457,7 +611,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| **Return value** @@ -465,11 +619,22 @@ Obtains the names of NICs in the specified network sharing state. This API uses | --------------------------------- | ------------------------------------- | | Promise\> | Promise used to return an array of NIC names.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { +let SHARING_BLUETOOTH=2; +sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js -import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { +import SharingIfaceType from '@ohos.net.sharing' +let SHARING_WIFI=0; +sharing.getSharingState(SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -523,6 +699,16 @@ Obtains the network sharing state of the specified type. This API uses a promise | -------- | --------------------------------------- | ---- | ---------- | | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Return value** | Type | Description | @@ -533,7 +719,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { +let SHARING_WIFI=0; +sharing.getSharingState(SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\> | Yes | Callback used to return an array of regular expressions.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { +let SHARING_WIFI=0; +sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -593,11 +791,22 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise | --------------------------------- | ------------------------------------- | | Promise\> | Promise used to return an array of regular expressions.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { +let SHARING_WIFI=0; +sharing.getSharableRegexes(SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -621,14 +830,20 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| +| callback | AsyncCallback\ | Yes | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingStateChange', (data) => { + console.log('on sharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -649,13 +864,19 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an | type | string | Yes | Event name.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('interfaceSharingStateChange', (data) => { + console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -705,13 +932,19 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('interfaceSharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -735,12 +968,18 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t | type | string | Yes | Event name.| | callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingUpstreamChange', (data) => { + console.log('on sharingUpstreamChange: ' + JSON.stringify(data)); }); ``` @@ -761,13 +1000,19 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback used for unsubscription from upstream network changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingUpstreamChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -788,7 +1033,7 @@ Enumerates the network sharing states of an NIC. ## SharingIfaceType -Enumerates the network sharing types of an NIC. +Enumerates the network sharing types of an NIC. **System API**: This is a system API. @@ -797,5 +1042,5 @@ Enumerates the network sharing types of an NIC. | Name | Value | Description | | ------------------------ | ---- | ---------------------- | | SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| -| SHARING_USB | 1 | USB sharing (not supported currently).| +| SHARING_USB | 1 | USB sharing.| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 2ad181cfd753f7ba9c2a3c42328f3d318e0af1e2..b0ad704b1848025f7b049f9c0cda6d12f2175554 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -853,8 +853,8 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -883,8 +883,8 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index 27962f40126ecdc7f533e17516378bb490797c4d..04ebebd0e2a3d3de98f8ce537eaa0cd3f9243013 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -24,7 +24,7 @@ Publishes a notification. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -78,7 +78,7 @@ Publishes a notification. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| **Error codes** @@ -130,7 +130,7 @@ Publishes a notification to a specified user. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | userId | number | Yes | User ID. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -192,7 +192,7 @@ Publishes a notification to a specified user. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | userId | number | Yes | User ID. | **Error codes** @@ -427,7 +427,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot to add.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -474,7 +474,7 @@ Adds a notification slot. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ---------------- | ---- | -------------------- | -| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot to add.| **Error codes** @@ -585,7 +585,7 @@ Adds an array of notification slots. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------ | -| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| slots | Array\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | Yes | Notification slots to add.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -636,7 +636,7 @@ Adds an array of notification slots. This API uses a promise to return the resul | Name | Type | Mandatory| Description | | ----- | ------------------------- | ---- | ------------------------ | -| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| slots | Array\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | Yes | Notification slots to add.| **Error codes** @@ -677,7 +677,7 @@ Obtains a notification slot of a specified type. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | | slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | Yes | Callback used to return the result. | **Error codes** @@ -757,7 +757,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | Callback used to return all notification slots of the current application.| +| callback | AsyncCallback\\> | Yes | Callback used to return all notification slots of the current application.| **Error codes** @@ -793,7 +793,7 @@ Obtains all notification slots of this application. This API uses a promise to r | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\\> | Promise used to return all notification slots of the current application.| +| Promise\\> | Promise used to return all notification slots of the current application.| **Error codes** @@ -965,7 +965,7 @@ Sets whether to enable notification for a specified application. This API uses a | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1012,7 +1012,7 @@ Sets whether to enable notification for a specified application. This API uses a | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| | enable | boolean | Yes | Whether to enable notification. | **Error codes** @@ -1053,7 +1053,7 @@ Checks whether notification is enabled for a specified application. This API use | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1099,7 +1099,7 @@ Checks whether notification is enabled for a specified application. This API use | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| **Return value** @@ -1187,7 +1187,7 @@ Checks whether notification is enabled for the current application. This API use | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| **Return value** @@ -1230,7 +1230,7 @@ Sets whether to enable the notification badge for a specified application. This | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1277,7 +1277,7 @@ Sets whether to enable the notification badge for a specified application. This | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| | enable | boolean | Yes | Whether to enable notification. | **Error codes** @@ -1318,7 +1318,7 @@ Checks whether the notification badge is enabled for a specified application. Th | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1364,7 +1364,7 @@ Checks whether the notification badge is enabled for a specified application. Th | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| **Return value** @@ -1483,8 +1483,8 @@ Sets the notification slot for a specified application. This API uses an asynchr | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | -| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1533,8 +1533,8 @@ Sets the notification slot for a specified application. This API uses a promise | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| -| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot.| **Error codes** @@ -1577,8 +1577,8 @@ Obtains the notification slots of a specified application. This API uses an asyn | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Error codes** @@ -1623,13 +1623,13 @@ Obtains the notification slots of a specified application. This API uses a promi | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| **Return value** | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise> | Promise used to return the result.| +| Promise> | Promise used to return the result.| **Error codes** @@ -1669,7 +1669,7 @@ Obtains the number of notification slots of a specified application. This API us | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1715,7 +1715,7 @@ Obtains the number of notification slots of a specified application. This API us | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| **Return value** @@ -1762,7 +1762,7 @@ Obtains all active notifications. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Error codes** @@ -1788,7 +1788,7 @@ notificationManager.getAllActiveNotifications(getAllActiveNotificationsCallback) ## notificationManager.getAllActiveNotifications -getAllActiveNotifications(): Promise\\> +getAllActiveNotifications(): Promise\\> Obtains all active notifications. This API uses a promise to return the result. @@ -1802,7 +1802,7 @@ Obtains all active notifications. This API uses a promise to return the result. | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\\> | Promise used to return the result.| +| Promise\\> | Promise used to return the result.| **Error codes** @@ -1904,7 +1904,7 @@ Obtains active notifications of this application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Error codes** @@ -1932,7 +1932,7 @@ notificationManager.getActiveNotifications(getActiveNotificationsCallback); ## notificationManager.getActiveNotifications -getActiveNotifications(): Promise\\> +getActiveNotifications(): Promise\\> Obtains active notifications of this application. This API uses a promise to return the result. @@ -1942,7 +1942,7 @@ Obtains active notifications of this application. This API uses a promise to ret | Type | Description | | ------------------------------------------------------------ | --------------------------------------- | -| Promise\\> | Promise used to return the result.| +| Promise\\> | Promise used to return the result.| **Error codes** @@ -1974,7 +1974,7 @@ Cancels notifications under a notification group of this application. This API u | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------- | -| groupName | string | Yes | Name of the notification group, which is specified through [NotificationRequest](#notificationrequest) when the notification is published.| +| groupName | string | Yes | Name of the notification group, which is specified through [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) when the notification is published.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -2052,7 +2052,7 @@ Removes notifications under a notification group of a specified application. Thi | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2100,7 +2100,7 @@ Removes notifications under a notification group of a specified application. Thi | Name | Type | Mandatory| Description | | --------- | ------------ | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group.| **Error codes** @@ -2743,7 +2743,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function setDistributedEnableCallback() { +function setDistributedEnableCallback(err) { if (err) { console.error(`setDistributedEnable failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2888,7 +2888,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether the device supports distributed notifications. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2942,7 +2942,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether the device supports distributed notifications. | **Error codes** @@ -2987,7 +2987,7 @@ Checks whether a specified application supports distributed notifications. This | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -3005,7 +3005,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function isDistributedEnabledByBundleCallback(data) { +function isDistributedEnabledByBundleCallback(err, data) { if (err) { console.error(`isDistributedEnabledByBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3036,7 +3036,7 @@ Checks whether a specified application supports distributed notifications. This | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | **Return value** @@ -3164,7 +3164,7 @@ Publishes a notification through the reminder agent. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | | userId | number | Yes | User ID. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -3231,7 +3231,7 @@ Publishes a notification through the reminder agent. This API uses a promise to | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | | userId | number | Yes | User ID. | @@ -3391,9 +3391,9 @@ Sets whether to enable a specified notification slot type for a specified applic | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type. | -| enable | boolean | Yes | Whether to enable notification. | +| enable | boolean | Yes | Whether to enable the notification slot type. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -3442,7 +3442,7 @@ Sets whether to enable a specified notification slot type for a specified applic | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type.| | enable | boolean | Yes | Whether to enable notification. | @@ -3485,7 +3485,7 @@ Checks whether a specified notification slot type is enabled for a specified app | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -3534,7 +3534,7 @@ Checks whether a specified notification slot type is enabled for a specified app | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type.| **Return value** @@ -3809,16 +3809,6 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => | LEVEL_HIGH | 4 | Notification is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| -## BundleOption - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | Yes | Yes | Bundle information of the application.| -| uid | number | Yes | Yes | User ID.| - - ## SlotType **System capability**: SystemCapability.Notification.Notification @@ -3832,227 +3822,6 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => | OTHER_TYPES | 0xFFFF | Notification slot for other purposes.| -## NotificationActionButton - -Describes the button displayed in the notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | -| title | string | Yes | Yes | Button title. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| -| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | -| userInput | [NotificationUserInput](#notificationuserinput) | Yes | Yes | User input object. | - - -## NotificationBasicContent - -Describes the normal text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | ------ | ---- | ---- | ---------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| - - -## NotificationLongTextContent - -Describes the long text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | ------ | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| longText | string | Yes | Yes | Long text of the notification. | -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | - - -## NotificationMultiLineContent - -Describes the multi-line text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | --------------- | --- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| lines | Array\ | Yes | Yes | Multi-line text of the notification. | - - -## NotificationPictureContent - -Describe the picture-attached notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | - - -## NotificationContent - -Describes the notification content. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | -| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | -| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | -| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| -| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | -| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | - - -## NotificationFlagStatus - -Describes the notification flag status. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------- | --- | --------------------------------- | -| TYPE_NONE | 0 | The default flag is used. | -| TYPE_OPEN | 1 | The notification flag is enabled. | -| TYPE_CLOSE | 2 | The notification flag is disabled. | - - -## NotificationFlags - -Enumerates notification flags. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | -| soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable the sound alert for the notification. | -| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable vibration for the notification. | - - -## NotificationRequest - -Describes the notification request. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | -| content | [NotificationContent](#notificationcontent) | Yes | Yes | Notification content. | -| id | number | Yes | Yes | Notification ID. | -| slotType | [SlotType](#slottype) | Yes | Yes | Notification slot type. | -| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | -| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | -| deliveryTime | number | Yes | Yes | Time when the notification is sent. | -| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | -| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked.| -| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | -| color | number | Yes | Yes | Background color of the notification. Not supported currently.| -| colorEnabled | boolean | Yes | Yes | Whether the notification background color can be enabled. Not supported currently.| -| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| -| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | -| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | -| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon in the status bar. | -| label | string | Yes | Yes | Notification label. | -| badgeIconStyle | number | Yes | Yes | Notification badge type. | -| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | -| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to three buttons are allowed. | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| -| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | -| creatorUid | number | Yes | No | UID used for creating the notification. | -| creatorPid | number | Yes | No | PID used for creating the notification. | -| creatorUserId| number | Yes | No | ID of the user who creates the notification. | -| hashCode | string | Yes | No | Unique ID of the notification. | -| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName| string | Yes | Yes | Notification group name. | -| template | [NotificationTemplate](#notificationtemplate) | Yes | Yes | Notification template. | -| isRemoveAllowed | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption | [DistributedOptions](#distributedoptions) | Yes | Yes | Distributed notification options. | -| deviceId | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags | [NotificationFlags](#notificationflags) | Yes | No | Notification flags. | -| removalWantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber | number | Yes | Yes | Number of notifications displayed on the application icon. | - - -## DistributedOptions - -Describes distributed options. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | -| isDistributed | boolean | Yes | Yes | Whether the notification is a distributed notification. | -| supportDisplayDevices | Array\ | Yes | Yes | List of the devices to which the notification can be synchronized. | -| supportOperateDevices | Array\ | Yes | Yes | List of the devices on which the notification can be opened. | -| remindType | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | - - -## NotificationSlot - -Describes the notification slot. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | -| type | [SlotType](#slottype) | Yes | Yes | Notification slot type. | -| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | string | Yes | Yes | Notification slot description. | -| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | -| bypassDnd | boolean | Yes | Yes | Whether to bypass DND mode in the system. | -| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | boolean | Yes | Yes | Whether vibration is enabled for the notification. | -| sound | string | Yes | Yes | Notification alert tone. | -| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | -| lightColor | number | Yes | Yes | Indicator color of the notification. | -| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | -| enabled9+ | boolean | Yes | No | Whether the notification slot is enabled. | - - -## NotificationTemplate - -Describes the notification template. - -**System capability**: SystemCapability.Notification.Notification - -| Name| Type | Readable| Writable| Description | -| ---- | ---------------------- | ---- | ---- | ---------- | -| name | string | Yes | Yes | Template name.| -| data | {[key:string]: Object} | Yes | Yes | Template data.| - - -## NotificationUserInput - -Provides the notification user input. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------- | ------ | --- | ---- | ----------------------------- | -| inputKey | string | Yes | Yes | Key to identify the user input.| ## DeviceRemindType diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 0cefd840d31e7471f1976042d8ba3f322de74882..da9e5c8cceb2c106516dfc82e28a77a432a1edea 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -30,8 +30,8 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Notification subscription information.| +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | Yes | Notification subscriber. | +| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | Yes | Notification subscription information.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -83,7 +83,7 @@ Subscribes to notifications of all applications under this user. This API uses a | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | Yes | Notification subscriber. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -133,8 +133,8 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Notification subscription information. | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | Yes | Notification subscriber.| +| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | No | Notification subscription information. | **Error codes** @@ -178,7 +178,7 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | -------------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | Yes | Notification subscriber. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -201,8 +201,8 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -226,7 +226,7 @@ Unsubscribes from a notification. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | Yes | Notification subscriber.| **Error codes** @@ -241,8 +241,8 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```js -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -268,8 +268,8 @@ Removes a notification for a specified application. This API uses an asynchronou | Name | Type | Mandatory| Description | | --------------- | ----------------------------------| ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | +| notificationKey | [NotificationKey](js-apis-notification.md#notificationkey) | Yes | Notification key. | | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -324,8 +324,8 @@ Removes a notification for a specified application. This API uses a promise to r | Name | Type | Mandatory| Description | | --------------- | --------------- | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| -| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application.| +| notificationKey | [NotificationKey]((js-apis-notification.md#notificationkey)) | Yes | Notification key. | | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | **Error codes** @@ -372,7 +372,7 @@ Removes a specified notification. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](#onconsume) callback.| +| hashCode | string | Yes | Unique notification ID. It is the value of **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) in the [onConsume](#onconsume) callback. | | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -459,7 +459,7 @@ Removes all notifications for a specified application. This API uses an asynchro | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -547,7 +547,7 @@ Removes all notifications for a specified application. This API uses a promise t | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | No | Bundle information of the application.| +| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | No | Bundle information of the application.| **Error codes** @@ -668,7 +668,7 @@ Provides callbacks for receiving or removing notifications and serves as the inp ### onConsume -onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void +onConsume?: (data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void Callback for receiving notifications. @@ -680,7 +680,7 @@ Callback for receiving notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification received.| +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification received.| **Example** @@ -708,7 +708,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onCancel -onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void +onCancel?:(data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void Callback for canceling notifications. @@ -720,7 +720,7 @@ Callback for canceling notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification to cancel.| +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification to cancel.| **Example** @@ -748,7 +748,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onUpdate -onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void +onUpdate?:(data: [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) => void Callback for notification sorting updates. @@ -760,7 +760,7 @@ Callback for notification sorting updates. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Latest notification sorting list.| +| data | [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) | Yes| Latest notification sorting list.| **Example** @@ -935,7 +935,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onEnabledNotificationChanged -onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata)) => void +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata)) => void Listens for the notification enabled status changes. This API uses an asynchronous callback to return the result. @@ -947,7 +947,7 @@ Listens for the notification enabled status changes. This API uses an asynchrono | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata)\> | Yes| Callback used to return the result.| +| callback | AsyncCallback\<[EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata)\> | Yes| Callback used to return the result.| **Example** @@ -1013,104 +1013,6 @@ let subscriber = { notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` -## BundleOption - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | Yes | Yes | Bundle information of the application.| -| uid | number | Yes | Yes | User ID.| - -## NotificationKey - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | --- | -------- | -| id | number | Yes | Yes | Notification ID. | -| label | string | Yes | Yes | Notification label.| - -## SubscribeCallbackData - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable | Writable | Description | -| --------------- | ------------------------------------------------- | -------- | -------- | -------- | -| request | [NotificationRequest](js-apis-notificationManager.md#notificationrequest) | Yes| No| Notification content.| -| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes| No| Notification sorting information.| -| reason | number | Yes | No | Reason for deletion.| -| sound | string | Yes | No | Sound used for notification.| -| vibrationValues | Array\ | Yes | No | Vibration used for notification.| - - -## EnabledNotificationCallbackData - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable | Writable | Description | -| ------ | ------- | ---------------- | ---------------- | ---------------- | -| bundle | string | Yes| No| Bundle name of the application. | -| uid | number | Yes| No| UID of the application. | -| enable | boolean | Yes| No| Notification enabled status of the application.| - - -## NotificationSorting - -Provides sorting information of active notifications. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| -------- | ------------------------------------- | ---- | --- | ------------ | -| slot | [NotificationSlot](js-apis-notificationManager.md#notificationslot) | Yes | No | Notification slot.| -| hashCode | string | Yes | No | Unique ID of the notification.| -| ranking | number | Yes | No | Notification sequence number.| - - -## NotificationSortingMap - -Provides sorting information of active notifications in all subscribed notifications. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | -| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | No | Array of notification sorting information.| -| sortedHashCode | Array\ | Yes | No | Array of unique notification IDs.| - - -## NotificationSubscribeInfo - -Provides the information about the publisher for notification subscription. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------- | --------------- | --- | ---- | ------------------------------- | -| bundleNames | Array\ | Yes | Yes | Bundle names of the applications whose notifications are to be subscribed to.| -| userId | number | Yes | Yes | User whose notifications are to be subscribed to. | - - -## NotificationUserInput - -Provides the notification user input. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------- | ------ | --- | ---- | ----------------------------- | -| inputKey | string | Yes | Yes | Key to identify the user input.| ## RemoveReason diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index ae5b7999bd7e579179920a73fcaea6116890ff70..2d56d02d2ec4e0f2117266569cb5bfd905f1b338 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -9,7 +9,7 @@ The **observer** module provides event subscription management functions. You ca ## Modules to Import -```js +``` import observer from '@ohos.telephony.observer' ``` @@ -17,7 +17,7 @@ import observer from '@ohos.telephony.observer' on\(type: \'networkStateChange\', callback: Callback\): void; -Registers an observer for network status change events. This API uses an asynchronous callback to return the result. +Registers an observer for network status change events. This API uses an asynchronous callback to return the execution result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -30,6 +30,18 @@ Registers an observer for network status change events. This API uses an asynchr | type | string | Yes | Network status change event. | | callback | Callback\<[NetworkState](js-apis-radio.md#networkstate)\> | Yes | Callback used to return the result. For details, see [NetworkState](js-apis-radio.md#networkstate).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -43,7 +55,7 @@ observer.on('networkStateChange', data =>{ on\(type: \'networkStateChange\', options: { slotId: number }, callback: Callback\): void; -Registers an observer for network status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Registers an observer for network status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -54,9 +66,21 @@ Registers an observer for network status change events of the SIM card in the sp | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | type | string | Yes | Network status change event. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | Callback\<[NetworkState](js-apis-radio.md#networkstate)\> | Yes | Callback used to return the result. For details, see [NetworkState](js-apis-radio.md#networkstate).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -70,7 +94,7 @@ observer.on('networkStateChange', {slotId: 0}, data =>{ off\(type: \'networkStateChange\', callback?: Callback\): void; -Unregisters the observer for network status change events. This API uses an asynchronous callback to return the result. +Unregisters the observer for network status change events. This API uses an asynchronous callback to return the execution result. >**NOTE** > @@ -85,6 +109,14 @@ Unregisters the observer for network status change events. This API uses an asyn | type | string | Yes | Network status change event. | | callback | Callback\<[NetworkState](js-apis-radio.md#networkstate)\> | No | Callback used to return the result. For details, see [NetworkState](js-apis-radio.md#networkstate).| +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -101,7 +133,7 @@ observer.off('networkStateChange'); on\(type: \'signalInfoChange\', callback: Callback\>): void; -Registers an observer for signal status change events. This API uses an asynchronous callback to return the result. +Registers an observer for signal status change events. This API uses an asynchronous callback to return the execution result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -109,9 +141,21 @@ Registers an observer for signal status change events. This API uses an asynchro | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Signal status change event. | +| type | string | Yes | Signal information change event. | | callback | Callback\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -125,7 +169,7 @@ observer.on('signalInfoChange', data =>{ on\(type: \'signalInfoChange\', options: { slotId: number }, callback: Callback\>): void; -Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -133,10 +177,22 @@ Registers an observer for signal status change events of the SIM card in the spe | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| type | string | Yes | Signal status change event. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | string | Yes | Signal information change event. | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | Callback\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -150,7 +206,7 @@ observer.on('signalInfoChange', {slotId: 0}, data =>{ off\(type: \'signalInfoChange\', callback?: Callback\>): void; -Unregisters the observer for signal status change events. This API uses an asynchronous callback to return the result. +Unregisters the observer for signal status change events. This API uses an asynchronous callback to return the execution result. >**NOTE** > @@ -162,9 +218,20 @@ Unregisters the observer for signal status change events. This API uses an async | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Signal status change event. | +| type | string | Yes | Signal information change event. | | callback | Callback\> | No | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -182,7 +249,7 @@ observer.off('signalInfoChange'); on(type: 'callStateChange', callback: Callback\<{ state: CallState, number: string }\>): void; -Registers an observer for call status change events. This API uses an asynchronous callback to return the result. +Registers an observer for call status change events. This API uses an asynchronous callback to return the execution result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -193,6 +260,17 @@ Registers an observer for call status change events. This API uses an asynchrono | type | string | Yes | Call status change event. | | callback | Callback\<{ state: [CallState](js-apis-call.md#callstate), number: string }\> | Yes | Callback function. For details, see [CallState](js-apis-call.md#callstate) in call.
**number**: phone number.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -206,7 +284,7 @@ observer.on('callStateChange', value =>{ on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ state:CallState, number: string }>): void; -Registers an observer for call status change events. This API uses an asynchronous callback to return the result. +Registers an observer for call status change events. This API uses an asynchronous callback to return the execution result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -215,9 +293,20 @@ Registers an observer for call status change events. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Call status change event. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | Callback\<{ state: [CallState](js-apis-call.md#callstate), number: string }\> | Yes | Callback function. For details, see [CallState](js-apis-call.md#callstate) in call.
**number**: phone number.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -231,7 +320,7 @@ observer.on('callStateChange', {slotId: 0}, value =>{ off(type: 'callStateChange', callback?: Callback<{ state: CallState, number: string }>): void; -Unregisters the observer for call status change events. This API uses an asynchronous callback to return the result. +Unregisters the observer for call status change events. This API uses an asynchronous callback to return the execution result. >**NOTE** > @@ -246,6 +335,17 @@ Unregisters the observer for call status change events. This API uses an asynchr | type | string | Yes | Call status change event. | | callback | Callback\<{ state: [CallState](js-apis-call.md#callstate), number: string }\> | No | Callback function. For details, see [CallState](js-apis-call.md#callstate) in call.
**number**: phone number.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -263,7 +363,7 @@ observer.off('callStateChange'); on\(type: 'cellularDataConnectionStateChange', callback: Callback\<{ state: DataConnectState, network: RatType}\>\): void; -Registers an observer for connection status change events of the cellular data connection.This API uses an asynchronous callback to return the result. +Registers an observer for connection status change events of the cellular data link. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -271,9 +371,20 @@ Registers an observer for connection status change events of the cellular data c | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data connection. | +| type | string | Yes | Connection status change event of the cellular data link. | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -287,7 +398,7 @@ observer.on('cellularDataConnectionStateChange', value =>{ on\(type: 'cellularDataConnectionStateChange', options: { slotId: number }, callback: Callback\<{ state: DataConnectState, network: RatType }\>\): void; -Registers an observer for connection status change events of the cellular data connection over the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Registers an observer for connection status change events of the cellular data link over the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -295,10 +406,21 @@ Registers an observer for connection status change events of the cellular data c | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data connection. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | string | Yes | Connection status change event of the cellular data link. | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -312,7 +434,7 @@ observer.on('cellularDataConnectionStateChange', {slotId: 0}, value =>{ off\(type: 'cellularDataConnectionStateChange', callback?: Callback\<{ state: DataConnectState, network: RatType}\>\): void; -Unregisters the observer for connection status change events of the cellular data connection.This API uses an asynchronous callback to return the result. +Unregisters the observer for connection status change events of the cellular data link. This API uses an asynchronous callback to return the result. >**NOTE** > @@ -324,9 +446,20 @@ Unregisters the observer for connection status change events of the cellular dat | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data connection. | +| type | string | Yes | Connection status change event of the cellular data link. | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -355,6 +488,17 @@ Registers an observer for the uplink and downlink data flow status change events | type | string | Yes | Uplink and downlink data flow status change event of the cellular data service. | | callback | Callback\<[DataFlowType](js-apis-telephony-data.md#dataflowtype)\> | Yes | Callback used to return the result. For details, see [DataFlowType](js-apis-telephony-data.md#dataflowtype).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -377,9 +521,20 @@ Registers an observer for the uplink and downlink data flow status change events | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Uplink and downlink data flow status change event of the cellular data service. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | Callback\<[DataFlowType](js-apis-telephony-data.md#dataflowtype)\> | Yes | Callback used to return the result. For details, see [DataFlowType](js-apis-telephony-data.md#dataflowtype).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -408,6 +563,17 @@ Unregisters the observer for the uplink and downlink data flow status change eve | type | string | Yes | Uplink and downlink data flow status change event of the cellular data service. | | callback | Callback\<[DataFlowType](js-apis-telephony-data.md#dataflowtype)\> | No | Callback used to return the result. For details, see [DataFlowType](js-apis-telephony-data.md#dataflowtype).| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -436,6 +602,17 @@ Registers an observer for SIM card status change events. This API uses an asynch | type | string | Yes | SIM card status change event. | | callback | Callback\<[SimStateData](#simstatedata7)\> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -458,9 +635,20 @@ Registers an observer for status change events of the SIM card in the specified | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | SIM card status change event. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | Callback\<[SimStateData](#simstatedata7)\> | Yes | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -489,6 +677,17 @@ Unregisters the observer for SIM card status change events. This API uses an asy | type | string | Yes | SIM card status change event. | | callback | Callback\<[SimStateData](#simstatedata7)\> | No | Callback used to return the result.| +**Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -531,8 +730,8 @@ Enumerates SIM card types and states. **System capability**: SystemCapability.Telephony.StateRegistry -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| type | [CardType](js-apis-sim.md#cardtype) | Yes| SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| -| state | [SimState](js-apis-sim.md#simstate) | Yes| SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| -| reason8+ | [LockReason](#lockreason8) | Yes| SIM card lock type.| +| Name | Type | Mandatory| Description | +| ------------------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| type | [CardType](js-apis-sim.md#cardtype) | Yes | SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| +| state | [SimState](js-apis-sim.md#simstate) | Yes | SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| +| reason8+ | [LockReason](#lockreason8) | Yes | SIM card lock type. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index c7b8ecb87cca8ffe72417ca65c07086c8421fae1..94a4257dfcc0af730c79334f61473c4811cb3bfd 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -304,13 +304,13 @@ Checks whether an OS account is activated. This API uses a promise to return the } ``` -### checkConstraintEnabled9+ +### checkOsAccountConstraintEnabled9+ -checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback<boolean>): void +checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback<boolean>): void Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount @@ -337,25 +337,25 @@ Checks whether the specified constraint is enabled for an OS account. This API u let localId = 100; let constraint = "constraint.wifi"; try { - accountManager.checkConstraintEnabled(localId, constraint, (err, isEnabled)=>{ + accountManager.checkOsAccountConstraintEnabled(localId, constraint, (err, isEnabled)=>{ if (err) { - console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err)); + console.log("checkOsAccountConstraintEnabled failed, error: " + JSON.stringify(err)); } else { - console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled); + console.log("checkOsAccountConstraintEnabled successfully, isEnabled: " + isEnabled); } }); } catch (err) { - console.log("checkConstraintEnabled exception: " + JSON.stringify(err)); + console.log("checkOsAccountConstraintEnabled exception: " + JSON.stringify(err)); } ``` -### checkConstraintEnabled9+ +### checkOsAccountConstraintEnabled9+ -checkConstraintEnabled(localId: number, constraint: string): Promise<boolean> +checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise<boolean> Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount @@ -387,13 +387,13 @@ Checks whether the specified constraint is enabled for an OS account. This API u let localId = 100; let constraint = "constraint.wifi"; try { - accountManager.checkConstraintEnabled(localId, constraint).then((isEnabled) => { - console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled); + accountManager.checkOsAccountConstraintEnabled(localId, constraint).then((isEnabled) => { + console.log("checkOsAccountConstraintEnabled successfully, isEnabled: " + isEnabled); }).catch((err) => { - console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err)); + console.log("checkOsAccountConstraintEnabled failed, error: " + JSON.stringify(err)); }); } catch (err) { - console.log("checkConstraintEnabled exception: " + JSON.stringify(err)); + console.log("checkOsAccountConstraintEnabled exception: " + JSON.stringify(err)); } ``` @@ -973,9 +973,9 @@ Obtains the number of OS accounts created. This API uses a promise to return the } ``` -### queryOsAccountLocalIdFromProcess9+ +### getOsAccountLocalId9+ -queryOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void +getOsAccountLocalId(callback: AsyncCallback<number>): void Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. @@ -998,21 +998,21 @@ Obtains the ID of the OS account to which the current process belongs. This API ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryOsAccountLocalIdFromProcess((err, localId) => { + accountManager.getOsAccountLocalId((err, localId) => { if (err) { - console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalId failed, error: " + JSON.stringify(err)); } else { - console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId); + console.log("getOsAccountLocalId successfully, localId: " + localId); } }); } catch (err) { - console.log("queryOsAccountLocalIdFromProcess exception: " + JSON.stringify(err)); + console.log("getOsAccountLocalId exception: " + JSON.stringify(err)); } ``` -### queryOsAccountLocalIdFromProcess9+ +### getOsAccountLocalId9+ -queryOsAccountLocalIdFromProcess(): Promise<number> +getOsAccountLocalId(): Promise<number> Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result. @@ -1035,19 +1035,19 @@ Obtains the ID of the OS account to which the current process belongs. This API ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryOsAccountLocalIdFromProcess().then((localId) => { - console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId); + accountManager.getOsAccountLocalId().then((localId) => { + console.log("getOsAccountLocalId successfully, localId: " + localId); }).catch((err) => { - console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalId failed, error: " + JSON.stringify(err)); }); } catch (err) { - console.log('queryOsAccountLocalIdFromProcess exception: ' + JSON.stringify(err)); + console.log('getOsAccountLocalId exception: ' + JSON.stringify(err)); } ``` -### queryOsAccountLocalIdFromUid9+ +### getOsAccountLocalIdForUid9+ -queryOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void +getOsAccountLocalIdForUid(uid: number, callback: AsyncCallback<number>): void Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. @@ -1073,20 +1073,20 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou let accountManager = account_osAccount.getAccountManager(); let uid = 12345678; try { - accountManager.queryOsAccountLocalIdFromUid(uid, (err, localId) => { + accountManager.getOsAccountLocalIdForUid(uid, (err, localId) => { if (err) { - console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForUid failed, error: " + JSON.stringify(err)); } - console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId); + console.log("getOsAccountLocalIdForUid successfully, localId: " + localId); }); } catch (err) { - console.log("queryOsAccountLocalIdFromUid exception: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForUid exception: " + JSON.stringify(err)); } ``` -### queryOsAccountLocalIdFromUid9+ +### getOsAccountLocalIdForUid9+ -queryOsAccountLocalIdFromUid(uid: number): Promise<number> +getOsAccountLocalIdForUid(uid: number): Promise<number> Obtains the OS account ID based on the process UID. This API uses a promise to return the result. @@ -1117,19 +1117,19 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r let accountManager = account_osAccount.getAccountManager(); let uid = 12345678; try { - accountManager.queryOsAccountLocalIdFromUid(uid).then((localId) => { - console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId); + accountManager.getOsAccountLocalIdForUid(uid).then((localId) => { + console.log("getOsAccountLocalIdForUid successfully, localId: " + localId); }).catch((err) => { - console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForUid failed, error: " + JSON.stringify(err)); }); } catch (err) { - console.log('queryOsAccountLocalIdFromUid exception: ' + JSON.stringify(err)); + console.log('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err)); } ``` -### queryOsAccountLocalIdFromDomain9+ +### getOsAccountLocalIdForDomain9+ -queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void +getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void Obtains the OS account ID based on the domain account information. This API uses an asynchronous callback to return the result. @@ -1157,21 +1157,21 @@ Obtains the OS account ID based on the domain account information. This API uses let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryOsAccountLocalIdFromDomain(domainInfo, (err, localId) => { + accountManager.getOsAccountLocalIdForDomain(domainInfo, (err, localId) => { if (err) { - console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForDomain failed, error: " + JSON.stringify(err)); } else { - console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId); + console.log("getOsAccountLocalIdForDomain successfully, localId: " + localId); } }); } catch (err) { - console.log('queryOsAccountLocalIdFromDomain exception: ' + JSON.stringify(err)); + console.log('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); } ``` -### queryOsAccountLocalIdFromDomain9+ +### getOsAccountLocalIdForDomain9+ -queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> +getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise<number> Obtains the OS account ID based on the domain account information. This API uses a promise to return the result. @@ -1204,13 +1204,13 @@ Obtains the OS account ID based on the domain account information. This API uses let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; try { - accountManager.queryOsAccountLocalIdFromDomain(domainInfo).then((localId) => { - console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId); + accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId) => { + console.log("getOsAccountLocalIdForDomain successfully, localId: " + localId); }).catch((err) => { - console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForDomain failed, error: " + JSON.stringify(err)); }); } catch (err) { - console.log("queryOsAccountLocalIdFromDomain exception: " + JSON.stringify(err)); + console.log("getOsAccountLocalIdForDomain exception: " + JSON.stringify(err)); } ``` @@ -1456,9 +1456,9 @@ Obtains information about all the OS accounts created. This API uses a promise t } ``` -### getActivatedOsAccountIds9+ +### getActivatedOsAccountLocalIds9+ -getActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void +getActivatedOsAccountLocalIds(callback: AsyncCallback<Array<number>>): void Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. @@ -1481,21 +1481,21 @@ Obtains information about all activated OS accounts. This API uses an asynchrono ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getActivatedOsAccountIds((err, idArray)=>{ - console.log('getActivatedOsAccountIds err:' + JSON.stringify(err)); - console.log('getActivatedOsAccountIds idArray length:' + idArray.length); + accountManager.getActivatedOsAccountLocalIds((err, idArray)=>{ + console.log('getActivatedOsAccountLocalIds err:' + JSON.stringify(err)); + console.log('getActivatedOsAccountLocalIds idArray length:' + idArray.length); for(let i=0;i9+
+### getActivatedOsAccountLocalIds9+ -getActivatedOsAccountIds(): Promise<Array<number>> +getActivatedOsAccountLocalIds(): Promise<Array<number>> Obtains information about all activated OS accounts. This API uses a promise to return the result. @@ -1518,13 +1518,13 @@ Obtains information about all activated OS accounts. This API uses a promise to ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getActivatedOsAccountIds().then((idArray) => { - console.log('getActivatedOsAccountIds, idArray: ' + idArray); + accountManager.getActivatedOsAccountLocalIds().then((idArray) => { + console.log('getActivatedOsAccountLocalIds, idArray: ' + idArray); }).catch((err) => { - console.log('getActivatedOsAccountIds err: ' + JSON.stringify(err)); + console.log('getActivatedOsAccountLocalIds err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getActivatedOsAccountIds exception:' + JSON.stringify(e)); + console.log('getActivatedOsAccountLocalIds exception:' + JSON.stringify(e)); } ``` @@ -2214,9 +2214,9 @@ Sets a profile photo for an OS account. This API uses a promise to return the re } ``` -### queryOsAccountLocalIdBySerialNumber9+ +### getOsAccountLocalIdForSerialNumber9+ -queryOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void +getOsAccountLocalIdForSerialNumber(serialNumber: number, callback: AsyncCallback<number>): void Obtains the OS account ID based on the serial number (SN). This API uses an asynchronous callback to return the result. @@ -2243,7 +2243,7 @@ Obtains the OS account ID based on the serial number (SN). This API uses an asyn let accountManager = account_osAccount.getAccountManager(); let serialNumber = 12345; try { - accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ + accountManager.getOsAccountLocalIdForSerialNumber(serialNumber, (err, localId)=>{ console.log('ger localId err:' + JSON.stringify(err)); console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); }); @@ -2252,9 +2252,9 @@ Obtains the OS account ID based on the serial number (SN). This API uses an asyn } ``` -### queryOsAccountLocalIdBySerialNumber9+ +### getOsAccountLocalIdForSerialNumber9+ -queryOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> +getOsAccountLocalIdForSerialNumber(serialNumber: number): Promise<number> Obtains the OS account ID based on the SN. This API uses a promise to return the result. @@ -2286,19 +2286,19 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the let accountManager = account_osAccount.getAccountManager(); let serialNumber = 12345; try { - accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { - console.log('queryOsAccountLocalIdBySerialNumber localId: ' + localId); + accountManager.getOsAccountLocalIdForSerialNumber(serialNumber).then((localId) => { + console.log('getOsAccountLocalIdForSerialNumber localId: ' + localId); }).catch((err) => { - console.log('queryOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); + console.log('getOsAccountLocalIdForSerialNumber err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('queryOsAccountLocalIdBySerialNumber exception: ' + JSON.stringify(e)); + console.log('getOsAccountLocalIdForSerialNumber exception: ' + JSON.stringify(e)); } ``` -### querySerialNumberByOsAccountLocalId9+ +### getSerialNumberForOsAccountLocalId9+ -querySerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void +getSerialNumberForOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. @@ -2325,7 +2325,7 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch let accountManager = account_osAccount.getAccountManager(); let localId = 100; try { - accountManager.querySerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ + accountManager.getSerialNumberForOsAccountLocalId(localId, (err, serialNumber)=>{ console.log('ger serialNumber err:' + JSON.stringify(err)); console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); }); @@ -2334,9 +2334,9 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch } ``` -### querySerialNumberByOsAccountLocalId9+ +### getSerialNumberForOsAccountLocalId9+ -querySerialNumberByOsAccountLocalId(localId: number): Promise<number> +getSerialNumberForOsAccountLocalId(localId: number): Promise<number> Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result. @@ -2368,13 +2368,13 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise let accountManager = account_osAccount.getAccountManager(); let localId = 100; try { - accountManager.querySerialNumberByOsAccountLocalId(localId).then((serialNumber) => { - console.log('querySerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); + accountManager.getSerialNumberForOsAccountLocalId(localId).then((serialNumber) => { + console.log('getSerialNumberForOsAccountLocalId serialNumber: ' + serialNumber); }).catch((err) => { - console.log('querySerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); + console.log('getSerialNumberForOsAccountLocalId err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('querySerialNumberByOsAccountLocalId exception:' + JSON.stringify(e)); + console.log('getSerialNumberForOsAccountLocalId exception:' + JSON.stringify(e)); } ``` @@ -2462,9 +2462,9 @@ Unsubscribes from the OS account activation states, including the states of the } ``` -### getBundleIdFromUid9+ +### getBundleIdForUid9+ -getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; +getBundleIdForUid(uid: number, callback: AsyncCallback<number>): void; Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. @@ -2492,17 +2492,17 @@ Obtains the bundle ID based on the UID. This API uses an asynchronous callback t let accountManager = account_osAccount.getAccountManager(); let testUid = 1000000; try { - accountManager.getBundleIdFromUid(testUid, (err, bundleId) => { - console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); - console.info('getBundleIdFromUid bundleId:' + JSON.stringify(bundleId)); + accountManager.getBundleIdForUid(testUid, (err, bundleId) => { + console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); + console.info('getBundleIdForUid bundleId:' + JSON.stringify(bundleId)); }); } catch (e) { - console.info('getBundleIdFromUid exception:' + JSON.stringify(e)); + console.info('getBundleIdForUid exception:' + JSON.stringify(e)); } ``` -### getBundleIdFromUid9+ +### getBundleIdForUid9+ -getBundleIdFromUid(uid: number): Promise<number>; +getBundleIdForUid(uid: number): Promise<number>; Obtains the bundle ID based on the UID. This API uses a promise to return the result. @@ -2535,13 +2535,13 @@ Obtains the bundle ID based on the UID. This API uses a promise to return the re let accountManager = account_osAccount.getAccountManager(); let testUid = 1000000; try { - accountManager.getBundleIdFromUid(testUid).then((result) => { - console.info('getBundleIdFromUid bundleId:' + JSON.stringify(result)); + accountManager.getBundleIdForUid(testUid).then((result) => { + console.info('getBundleIdForUid bundleId:' + JSON.stringify(result)); }).catch((err)=>{ - console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); + console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('getBundleIdFromUid exception:' + JSON.stringify(e)); + console.info('getBundleIdForUid exception:' + JSON.stringify(e)); } ``` @@ -2620,9 +2620,9 @@ Checks whether the current process belongs to the main OS account. This API uses console.info('isMainOsAccount exception:' + JSON.stringify(e)); } ``` -### queryOsAccountConstraintSourceTypes9+ +### getOsAccountConstraintSourceTypes9+ -queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; +getOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. @@ -2653,18 +2653,18 @@ Obtains the constraint source information of an OS account. This API uses an asy ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{ - console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); - console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); + accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{ + console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); + console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); }); } catch (e) { - console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); + console.info('getOsAccountConstraintSourceTypes exception:' + JSON.stringify(e)); } ``` -### queryOsAccountConstraintSourceTypes9+ +### getOsAccountConstraintSourceTypes9+ -queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; +getOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; Obtains the constraint source information of an OS account. This API uses a promise to return the result. @@ -2700,13 +2700,13 @@ Obtains the constraint source information of an OS account. This API uses a prom ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => { - console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(result)); + accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => { + console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(result)); }).catch((err)=>{ - console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); + console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); + console.info('getOsAccountConstraintSourceTypes exception:' + JSON.stringify(e)); } ``` @@ -2852,7 +2852,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountConstraintEnabled](#checkosaccountconstraintenabled9). **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -2889,7 +2889,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9-1). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountConstraintEnabled](#checkosaccountconstraintenabled9-1). **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -3158,7 +3158,7 @@ Obtains the ID of the OS account to which the current process belongs. This API > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalId](#getosaccountlocalid9). **System capability**: SystemCapability.Account.OsAccount @@ -3189,7 +3189,7 @@ Obtains the ID of the OS account to which the current process belongs. This API > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9-1). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalId](#getosaccountlocalid9-1). **System capability**: SystemCapability.Account.OsAccount @@ -3218,7 +3218,7 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForUid](#getosaccountlocalidforuid9). **System capability**: SystemCapability.Account.OsAccount @@ -3251,7 +3251,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9-1). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForUid](#getosaccountlocalidforuid9-1). **System capability**: SystemCapability.Account.OsAccount @@ -3287,7 +3287,7 @@ Obtains the OS account ID based on the domain account information. This API uses > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForDomain](#getosaccountlocalidfordomain9). **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -3322,7 +3322,7 @@ Obtains the OS account ID based on the domain account information. This API uses > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9-1). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForDomain](#getosaccountlocalidfordomain9-1). **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -3430,7 +3430,7 @@ Obtains information about all activated OS accounts. This API uses an asynchrono > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountLocalIds](#getactivatedosaccountlocalids9). **System capability**: SystemCapability.Account.OsAccount @@ -3459,7 +3459,7 @@ queryActivatedOsAccountIds(): Promise<Array<number>> > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9-1). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountLocalIds](#getactivatedosaccountlocalids9-1). Obtains information about all activated OS accounts. This API uses a promise to return the result. @@ -3669,7 +3669,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForSerialNumber](#getosaccountlocalidforserialnumber9). **System capability**: SystemCapability.Account.OsAccount @@ -3695,11 +3695,11 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the serial number. This API uses a promise to return the result. +Obtains the OS account ID based on the SN. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9-1). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForSerialNumber](#getosaccountlocalidforserialnumber9-1). **System capability**: SystemCapability.Account.OsAccount @@ -3735,7 +3735,7 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSerialNumberForOsAccountLocalId](#getserialnumberforosaccountlocalid9). **System capability**: SystemCapability.Account.OsAccount @@ -3765,7 +3765,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9-1). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSerialNumberForOsAccountLocalId](#getserialnumberforosaccountlocalid9-1). **System capability**: SystemCapability.Account.OsAccount diff --git a/en/application-dev/reference/apis/js-apis-overlay.md b/en/application-dev/reference/apis/js-apis-overlay.md new file mode 100644 index 0000000000000000000000000000000000000000..61181d1767aeb33951b983163b376478cf3d1f36 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-overlay.md @@ -0,0 +1,693 @@ +# @ohos.bundle.overlay (overlay) + +The **overlay** module provides APIs for installing a [module with the overlay feature](#module-with-the-overlay-feature), querying the [module information](js-apis-bundleManager-overlayModuleInfo.md), and disabling and enabling the module. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +``` ts +import overlay from '@ohos.bundle.overlay' +``` + +## overlay.setOverlayEnabled + +setOverlayEnabled(moduleName:string, isEnabled: boolean): Promise\; + +Enables or disables a module with the overlay feature in the current application. This API uses a promise to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var moduleName = "feature"; +var isEnabled = false; + +try { + overlay.setOverlayEnabled(moduleName, isEnabled) + .then(() => { + console.info('setOverlayEnabled success'); + }).catch((error) => { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }); +} catch (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabled + +setOverlayEnabled(moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void; + +Enables or disables a module with the overlay feature in the current application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var moduleName = "feature"; +var isEnabled = false; + +try { + overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => { + if (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + return; + } + console.info('setOverlayEnabled success'); + }); +} catch (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabledByBundleName + +setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean): Promise\; + +Enables or disables a module with the overlay feature in another application. This API uses a promise to return the result. If the operation is successful, the processing result is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.CHANGE_OVERLAY_ENABLED_STATE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" +var isEnabled = false; + +try { + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) + .then((data) => { + console.info('setOverlayEnabledByBundleName successfully'); + }).catch((error) => { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }); +} catch (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabledByBundleName + +setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void; + +Enables or disables a module with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, the processing result is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.CHANGE_OVERLAY_ENABLED_STATE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the processing result obtained; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" +var isEnabled = false; + +try { + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => { + if (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + return; + } + console.info('setOverlayEnabledByBundleName successfully'); + }); +} catch (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.getOverlayModuleInfo + +getOverlayModuleInfo(moduleName: string): Promise\; + +Obtains the information about a module with the overlay feature in the current application. This API uses a promise to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ------------------------------------------ | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the result, which is an **OverlayModuleInfo** object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName); + console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo)); + } catch(err) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getOverlayModuleInfo + +getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\): void; + +Obtains the information about a module with the overlay feature in the current application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | Yes | HAP name of the module with the overlay feature. | +| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an **OverlayModuleInfo** object. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var moduleName = "feature" +try { + overlay.getOverlayModuleInfo(moduleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfos + +getTargetOverlayModuleInfos(targetModuleName: string): Promise\>; + +Obtains the information about modules with the overlay feature in the current application based on the target module name. This API uses a promise to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| targetModuleName | string | Yes | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\> | Promise used to return the result, which is an array of **OverlayModuleInfo** objects.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | + +**Example** + +```ts +var targetModuleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getTargetOverlayModuleInfos + +getTargetOverlayModuleInfos(targetModuleName: string, callback: AsyncCallback\>): void; + +Obtains the information about modules with the overlay feature in the current application based on the target module name. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| targetModuleName | string | Yes | HAP name of the target module specified by modules with the overlay feature. | +| callback | AsyncCallback\> | Yes | Callback used to return the result, which is an array of **OverlayModuleInfo** objects. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | + +**Example** + +```ts +var targetModuleName = "feature" +try { + overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promise\>; + +Obtains the information about a module with the overlay feature in another application. This API uses a promise to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| moduleName | string | No | HAP name of the module with the overlay feature. If this parameter is not specified, the API obtains the information of all modules with the overlay feature in that application. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\> | Promise used to return the result, which is an array of **OverlayModuleInfo** objects.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callback: AsyncCallback\>): void; + +Obtains the information about a module with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| moduleName | string | Yes | HAP name of the module with the overlay feature. If this parameter is not specified, the API obtains the information of all modules with the overlay feature in that application. | +| callback | AsyncCallback\> | Yes | Callback used to return the result, which is an array of **OverlayModuleInfo** objects. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +try { + overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\>): void; + +Obtains the information about all modules with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\> | Yes | Callback used to return the result, which is an array of **OverlayModuleInfo** objects. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**Example** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; + +try { + overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: string): Promise\>; + +Obtains the information about modules with the overlay feature in another application based on the target module name. This API uses a promise to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | Yes | Bundle name of the application. | +| moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. If this parameter is not specified, the API obtains the information associated with all modules in that application. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\> | Promise used to return the result, which is an array of **OverlayModuleInfo** objects.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**Example** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\>): void; + +Obtains the information about modules with the overlay feature in another application based on the target module name. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | Yes | Bundle name of the application. | +| moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. If this parameter is not specified, the API obtains the information associated with all modules in that application. | +| callback | AsyncCallback\> | Yes | Callback used to return the result, which is an array of **OverlayModuleInfo** objects. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**Example** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +try { + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\>): void; + +Obtains the information about all modules with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\> | Yes | Callback used to return the result, which is an array of **OverlayModuleInfo** objects. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**Example** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; + +try { + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## Module with the Overlay Feature + +**Concept** +A module with the overlay feature generally provides additional resource files for modules without the overlay feature on the device, so that the target modules can use these resource files at runtime to display different colors, labels, themes, and the like. The overlay feature applies only to the stage model. + +**How do I identify a module with the overlay feature?** +If the **module.json5** file of a module contains the **targetModuleName** and **targetPriority fields** during project creation on DevEco Studio, the module is identified as a module with the overlay feature in the installation phase. diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index d1d554f677aca7fcb21d1e74cd6fb502f6e90032..bff07f3833aee97a4034ae54e8d8779cc9b194b9 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -3,7 +3,7 @@ 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 @@ -63,7 +63,7 @@ Creates a **PasteData** object of a custom type. ```js let dataXml = new ArrayBuffer(256); - let pasteData = pasteboard.createData('app/xml', dataXml); +let pasteData = pasteboard.createData('app/xml', dataXml); ``` ## pasteboard.createRecord9+ @@ -90,8 +90,8 @@ Creates a **PasteDataRecord** object of the custom type. **Example** ```js - let dataXml = new ArrayBuffer(256); - let pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); +let dataXml = new ArrayBuffer(256); +let pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); ``` ## pasteboard.getSystemPasteboard @@ -120,11 +120,11 @@ Enumerates the paste options of data. **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Value| Description | -| ---- |---|-------------------| -| InApp | 0 | Only intra-application pasting is allowed. | -| LocalDevice | 1 | Paste is allowed in any application on the local device.| -| CrossDevice | 2 | Paste is allowed in any application across devices. | +| Name | Value| Description | +|-------------|---|-------------------| +| INAPP | 0 | Only intra-application pasting is allowed. | +| LOCALDEVICE | 1 | Paste is allowed in any application on the local device.| +| CROSSDEVICE | 2 | Paste is allowed in any application across devices. | ## pasteboard.createHtmlData(deprecated) @@ -374,14 +374,14 @@ Defines the properties of all data records on the pasteboard, including the time **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| 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).| +| Name| Type| Readable| Writable| Description | +| -------- | -------- | -------- | -------- |--------------------------------------------------------------------------------------------| +| 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.| +| 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+ @@ -401,38 +401,11 @@ Provides **PasteDataRecord** APIs. A **PasteDataRecord** is an abstract definiti | pixelMap9+ | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| No| Pixel map.| | data9+ | {[mimeType: string]: ArrayBuffer} | Yes| No| Content of custom data.| -### convertToTextV99+ +### toPlainText9+ -convertToTextV9(callback: AsyncCallback<string>): void +toPlainText(): string -Forcibly converts the content in a **PasteData** object to text. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the text obtained from the conversion. Otherwise, **err** is error information.| - -**Example** - -```js -let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); -record.convertToTextV9((err, data) => { - if (err) { - console.error(`Failed to convert to text. Cause: ${err.message}`); - return; - } - console.info(`Succeeded in converting to text. Data: ${data}`); -}); -``` - -### convertToTextV99+ - -convertToTextV9(): Promise<string> - -Forcibly converts the content in a **PasteData** object to text. This API uses a promise to return the result. +Forcibly converts the content in a **PasteData** object to text. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -440,17 +413,14 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a | Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return the text obtained from the conversion.| +| string | Plain text.| **Example** ```js let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); -record.convertToTextV9().then((data) => { - console.info(`Succeeded in converting to text. Data: ${data}`); -}).catch((err) => { - console.error(`Failed to convert to text. Cause: ${err.message}`); -}); +let data = record.toPlainText(); +console.info(`Succeeded in converting to text. Data: ${data}`); ``` ### convertToText(deprecated) @@ -460,7 +430,7 @@ convertToText(callback: AsyncCallback<string>): void Forcibly converts the content in a **PasteData** object to text. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [convertToTextV9](#converttotextv99). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -474,8 +444,8 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a ```js let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); -record.convertToText((err, data) => { - if (err) { +record.convertToText((err, data) => { + if (err) { console.error(`Failed to convert to text. Cause: ${err.message}`); return; } @@ -490,7 +460,7 @@ convertToText(): Promise<string> Forcibly converts the content in a **PasteData** object to text. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [convertToTextV9](#converttotextv99-1). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -636,7 +606,7 @@ let opt = { scaleMode: 1 }; image.createPixelMap(buffer, opt).then((pixelMap) => { - let pasteData = pasteboard.createData(MIMETYPE_PIXELMAP, pixelMap); + let pasteData = pasteboard.createData(pasteboard.MIMETYPE_PIXELMAP, pixelMap); let PixelMap = pasteData.getPrimaryPixelMap(); }); ``` @@ -782,7 +752,7 @@ Sets the property (attributes) for the pasteboard data. Currently, only the **sh ```js let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_HTML, 'application/xml'); let prop = pasteData.getProperty(); -prop.shareOption = pasteboard.ShareOption.InApp; +prop.shareOption = pasteboard.ShareOption.INAPP; pasteData.setProperty(prop); ``` @@ -812,7 +782,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er | Error Code ID| Error Message| | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **Example** @@ -910,7 +880,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er | Error Code ID| Error Message| | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **Example** @@ -940,7 +910,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er | Error Code ID| Error Message| | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **Example** @@ -999,8 +969,8 @@ The pasteboard supports a maximum number of 512 data records. ```js let pasteData = pasteboard.createPlainTextData('hello'); -let object = { - bundleName: "com.example.aafwk.test", +let object = { + bundleName: "com.example.aafwk.test", abilityName: "com.example.aafwk.test.TwoAbility" }; pasteData.addWantRecord(object); @@ -1255,7 +1225,7 @@ Clears the system pasteboard. This API uses an asynchronous callback to return t ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.clearData((err, data) => { +systemPasteboard.clearData((err, data) => { if (err) { console.error(`Failed to clear the pasteboard. Cause: ${err.message}`); return; @@ -1282,7 +1252,7 @@ Clears the system pasteboard. This API uses a promise to return the result. ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.clearData().then((data) => { +systemPasteboard.clearData().then((data) => { console.info('Succeeded in clearing the pasteboard.'); }).catch((err) => { console.error(`Failed to clear the pasteboard. Cause: ${err.message}`); @@ -1318,7 +1288,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er ```js let pasteData = pasteboard.createPlainTextData('content'); let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setData(pasteData, (err, data) => { +systemPasteboard.setData(pasteData, (err, data) => { if (err) { console.error('Failed to set PasteData. Cause: ' + err.message); return; @@ -1394,7 +1364,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getData((err, pasteData) => { +systemPasteboard.getData((err, pasteData) => { if (err) { console.error('Failed to get PasteData. Cause: ' + err.message); return; @@ -1429,7 +1399,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getData().then((pasteData) => { +systemPasteboard.getData().then((pasteData) => { let text = pasteData.getPrimaryText(); }).catch((err) => { console.error('Failed to get PasteData. Cause: ' + err.message); @@ -1481,7 +1451,7 @@ Checks whether the system pasteboard contains data. This API uses a promise to r ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.hasData().then((data) => { +systemPasteboard.hasData().then((data) => { console.info(`Succeeded in checking the PasteData. Data: ${data}`); }).catch((err) => { console.error(`Failed to check the PasteData. Cause: ${err.message}`); @@ -1508,8 +1478,8 @@ Clears the system pasteboard. This API uses an asynchronous callback to return t **Example** ```js -systemPasteboard.clear((err, data) => { - if (err) { +systemPasteboard.clear((err, data) => { + if (err) { console.error(`Failed to clear the PasteData. Cause: ${err.message}`); return; } @@ -1537,9 +1507,9 @@ Clears the system pasteboard. This API uses a promise to return the result. **Example** ```js -systemPasteboard.clear().then((data) => { +systemPasteboard.clear().then((data) => { console.info('Succeeded in clearing the PasteData.'); -}).catch((err) => { +}).catch((err) => { console.error(`Failed to clear the PasteData. Cause: ${err.message}`); }); ``` @@ -1595,7 +1565,7 @@ Obtains a **PasteData** object from the pasteboard. This API uses a promise to r ```js let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getPasteData().then((pasteData) => { +systemPasteboard.getPasteData().then((pasteData) => { let text = pasteData.getPrimaryText(); }).catch((err) => { console.error('Failed to get PasteData. Cause: ' + err.message); @@ -1651,7 +1621,7 @@ Checks whether the system pasteboard contains data. This API uses a promise to r **Example** ```js -systemPasteboard.hasPasteData().then((data) => { +systemPasteboard.hasPasteData().then((data) => { console.info(`Succeeded in checking the PasteData. Data: ${data}`); }).catch((err) => { console.error(`Failed to check the PasteData. Cause: ${err.message}`); @@ -1681,7 +1651,7 @@ Writes a **PasteData** object to the pasteboard. This API uses an asynchronous c ```js let pasteData = pasteboard.createPlainTextData('content'); let systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setPasteData(pasteData, (err, data) => { +systemPasteboard.setPasteData(pasteData, (err, data) => { if (err) { console.error('Failed to set PasteData. Cause: ' + err.message); return; diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index 0a0a8ec3833247e78fe5ea513ab7d9383ebe92ac..eae4b4a3970507756fab9b96ff76b93b77154ca2 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -4,8 +4,8 @@ The **PermissionRequestResult** module defines the result of a permission reques > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Attributes @@ -14,7 +14,7 @@ The **PermissionRequestResult** module defines the result of a permission reques | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No|Result of the permission Request.
**-1**: The permission has been set and no dialog box will be displayed. Users can modify the permission in **Settings**.
**0**: No operation is required.
**1**: Dynamic user authorization is required via a dialog window .
**2**: The request is invalid. Possible causes are as follows:
- The permission is not declared in the configuration file.
- The permission name is invalid.
- Special conditions for applying for the permission do not satisfied. See [ohos.permission.LOCATION](../../security/permission-list.md#ohospermissionlocation) and [ohos.permission.APPROXIMATELY_LOCATION](../../security/permission-list.md#ohospermissionapproximately_location).| +| authResults | Array<number> | Yes| No| Result of the permission request.
- **-1**: The permission is not authorized and must be set in **Settings** without displaying a dialog box.
- **0**: The permission is authorized.
- **2**: The permission is not authorized due to an invalid request. The possible causes are as follows:
- The permission is not declared in the configuration file.
- The permission name is invalid.
- Special conditions for applying for the permission are not satisfied. See [ohos.permission.LOCATION](../../security/permission-list.md#ohospermissionlocation) and [ohos.permission.APPROXIMATELY_LOCATION](../../security/permission-list.md#ohospermissionapproximately_location).| ## Usage diff --git a/en/application-dev/reference/apis/js-apis-plugincomponent.md b/en/application-dev/reference/apis/js-apis-plugincomponent.md new file mode 100644 index 0000000000000000000000000000000000000000..740fd72e50247da5bdae3b573c1e115c8cdcd0e5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-plugincomponent.md @@ -0,0 +1,400 @@ +# @ohos.pluginComponent (PluginComponentManager) + +The **PluginComponentManager** module provides APIs for the **PluginComponent** user to request components and data and send component templates and data. For details about how to display the **PluginComponent** template, see [PluginComponent](../arkui-ts/ts-basic-components-plugincomponent.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import pluginComponentManager from '@ohos.pluginComponent' +``` + +## PluginComponentTemplate + +Describes the **PluginComponent** template parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | --------------------------- | +| source | string | Yes | Component template name. | +| bundleName | string | Yes | Bundle name of the provider ability.| + + +## PluginComponentManager + +### KVObject + +Stores information in key-value pairs in JSON format. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + +| Value Range | Description | +| --------------------- | ---------------------------------------- | +| [key: string] | Keyword. The value is a string and can be an empty string.| +| number | Key value of the number type. | +| string | Key value of the string type. The value can be an empty string.| +| boolean | Key value of the Boolean type. | +| [] | Key value. The value can be []. | +| [KVObject](#kvobject) | Key value of the KVObject type. | + + +### PushParameters + +Sets the parameters to be passed in the **PluginManager.Push** API in the FA model. + +**Model restriction**: This API can be used only in the FA model. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------- | ---- | -------------------------------------------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| name | string | Yes | Component name. | +| data | [KVObject](#kvobject) | No | Component data value. | +| extraData | [KVObject](#kvobject) | No | Additional data value. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| + +### PushParameterForStage + +Sets the parameters to be passed in the **PluginManager.Push** API in the stage model. + +**Model restriction**: This API can be used only in the stage model. + +**System API**: This is a system API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------- | ---- | ---------------------------------------------------------------- | +| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| name | string | Yes | Component name. | +| data | [KVObject](#kvobject) | No | Component data value. | +| extraData | [KVObject](#kvobject) | No | Additional data value. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| + +### RequestParameters + +Sets the parameters to be passed in the **PluginManager.Request** API in the FA model. + +**Model restriction**: This API can be used only in the FA model. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| name | string | Yes | Name of the requested component. | +| data | [KVObject](#kvobject) | Yes | Additional data. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| + +### RequestParameterForStage + +Sets the parameters to be passed in the **PluginManager.Request** API in the stage model. + +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------- | +| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| name | string | Yes | Name of the requested component. | +| data | [KVObject](#kvobject) | Yes | Additional data. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| + +### RequestCallbackParameters + +Provides the result returned after the **PluginManager.Request** API is called. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| ----------------- | ---------------------------------------------------- | ---- | ---------- | +| componentTemplate | [PluginComponentTemplate](#plugincomponenttemplate)] | Yes | Component template.| +| data | [KVObject](#kvobject) | Yes | Component data.| +| extraData | [KVObject](#kvobject) | Yes | Additional data.| + +### RequestEventResult + +Provides the result returned after the request listener is registered and the requested event is received. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------- | +| template | string | No | Component template.| +| data | [KVObject](#kvobject) | No | Component data.| +| extraData | [KVObject](#kvobject) | No | Additional data.| + +### OnPushEventCallback + +OnPushEventCallback = (source: Want, template: PluginComponentTemplate, data: KVObject, + extraData: KVObject) => void + +Registers the listener for the push event. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------------- | ---- | ---------------------------------------- | +| source | [Want](js-apis-application-want.md) | Yes | Information about the push request sender. | +| template | [PluginComponentTemplate](#plugincomponenttemplate) | Yes | Name of the request component template for the push request sender.| +| data | [KVObject](#kvobject) | Yes | Data. | +| extraData | [KVObject](#kvobject) | Yes | Additional data. | + +**Example** + +```js +function onPushListener(source, template, data, extraData) { + console.log("onPushListener template.source=" + template.source) + console.log("onPushListener source=" + JSON.stringify(source)) + console.log("onPushListener template=" + JSON.stringify(template)) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) +} +``` + + +### OnRequestEventCallback + +OnRequestEventCallback = (source: Want, name: string, data: KVObject) => RequestEventResult + +Registers the listener for the request event. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------- | ---- | --------------------------- | +| source | [Want](js-apis-application-want.md) | Yes | Information about the request sender.| +| data | [KVObject](#kvobject) | Yes | Data. | +| extraData | [KVObject](#kvobject) | Yes | Additional data. | + +**Example** + +```js +function onRequestListener(source, name, data) +{ + console.error("onRequestListener"); + console.log("onRequestListener source=" + JSON.stringify(source)); + console.log("onRequestListener name=" + name); + console.log("onRequestListener data=" + JSON.stringify(data)); + + return {template:"ets/pages/plugin.js", data:data}; +} +``` + +### push + +push(param: PushParameters , callback: AsyncCallback<void>): void + +Pushes the component and data to the component user. + +**Model restriction**: This API can be used only in the FA model. + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------ | +| param | [PushParameters](#pushparameters) | Yes | Information about the component user. | +| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| + +**Example** + +```js +pluginComponentManager.push( +{ + want: { + bundleName: "com.example.provider", + abilityName: "com.example.provider.MainAbility", + }, + name: "plugintemplate", + data: { + "key_1": "plugin component test", + "key_2": 34234 + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", + }, + (err, data) => { + console.log("push_callback: push ok!"); + } +) +``` + +### push + +push(param: PushParameterForStage, callback: AsyncCallback<void>): void + +Pushes the component and data to the component user. + +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the stage model. + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------ | +| param | [PushParameterForStage](#pushparameterforstage) | Yes | Information about the component user. | +| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| + +**Example** + +```js +pluginComponentManager.push( + { + owner:{ + bundleName:"com.example.provider", + abilityName:"com.example.provider.MainAbility" + }, + target: { + bundleName: "com.example.provider", + abilityName: "com.example.provider.MainAbility", + }, + name: "ets/pages/plugin2.js", + data: { + "js": "ets/pages/plugin.js", + "key_1": 1111, , + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", + }, + (err, data) => { + console.log("push_callback:err: " ,JSON.stringify(err)); + console.log("push_callback:data: " , JSON.stringify(data)); + console.log("push_callback: push ok!"); + } +) +``` + + +### request + +request(param: RequestParameters, callback: AsyncCallback<RequestCallbackParameters>): void + +Requests the component from the component provider. + +**Model restriction**: This API can be used only in the FA model. + + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------- | +| param | [RequestParameters](#requestparameters) | Yes | Information about the component request. | +| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| + +**Example** + +```js +pluginComponentManager.request( + { + want: { + bundleName: "com.example.provider", + abilityName: "com.example.provider.MainAbility", + }, + name: "plugintemplate", + data: { + "key_1": "plugin component test", + "key_2": 1111111 + }, + jsonPath: "", + }, + (err, data) => { + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + console.log("request_callback: data=" + JSON.stringify(data.data)) + console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) + } +) +``` + + +### request + +request(param: RequestParameterForStage, callback: AsyncCallback<RequestCallbackParameters>): void + +Requests the component from the component provider. + +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the stage model. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------- | +| param | [RequestParameterForStage](#requestparameterforstage) | Yes | Information about the component request. | +| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| + +**Example** + +```js +pluginComponentManager.request( + { + owner:{ + bundleName:"com.example.provider", + abilityName:"com.example.provider.MainAbility" + }, + target: { + bundleName: "com.example.provider", + abilityName: "ets/pages/plugin2.js", + }, + name: "plugintemplate", + data: { + "key_1": " myapplication plugin component test", + }, + jsonPath: "", + }, + (err, data) => { + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + } +) +``` + +### on + +on(eventType: string, callback: OnPushEventCallback | OnRequestEventCallback ): void + +Listens for events of the request type and returns the requested data, or listens for events of the push type and receives the data pushed by the provider. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| eventType | string | Yes | Type of the event to listen for. The options are as follows:
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider. | +| callback | [OnPushEventCallback](#onpusheventcallback) \| [OnRequestEventCallback](#onrequesteventcallback) | Yes | Callback used to return the result. The type is [OnPushEventCallback](#onpusheventcallback) for the push event and [OnRequestEventCallback](#onrequesteventcallback) for the request event.| + + +**Example** + +```js + pluginComponentManager.on("push", onPushListener) + pluginComponentManager.on("request", onRequestListener) +``` + +## About the external.json File + +The **external.json** file is created by developers. It stores component names and template paths in key-value pairs. The component name is used as the keyword, and the corresponding template path is used as the value. + +**Example** + +```json +{ + "PluginProviderExample": "ets/pages/PluginProviderExample.js", + "plugintemplate2": "ets/pages/plugintemplate2.js" +} + +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 8ed463d9a5bbbeb6ca8e12212e256e6a4ae3fbec..49ed81e115de6345453c93441b68cda2a132021b 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -2,7 +2,8 @@ The **pointer** module provides APIs related to pointer attribute management. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result. **System capability**: SystemCapability.MultimodalInput.Input.Pointer +**System API**: This is a system API. + **Return value** | Name | Description | @@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur **System capability**: SystemCapability.MultimodalInput.Input.Pointer -**System API**: This is a system API. - **Parameters** | Name | Type | Mandatory | Description | @@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getWindowProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.getPointerStyle(windowId, (error, style) => { - console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); - }); - } catch (error) { - console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId, (error, style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); + }); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` @@ -320,21 +323,23 @@ Obtains the mouse pointer style. This API uses a promise to return the result. ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getWindowProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.getPointerStyle(windowId).then((style) => { - console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); - }); - } catch (error) { - console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId).then((style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); + }); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` @@ -359,21 +364,23 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getWindowProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { - console.log(`Set pointer style success`); - }); - } catch (error) { - console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` ## pointer.setPointerStyle9+ @@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result. ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getWindowProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { - console.log(`Set pointer style success`); - }); - } catch (error) { - console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` ## PointerStyle9+ @@ -420,44 +429,44 @@ Enumerates mouse pointer styles. **System capability**: SystemCapability.MultimodalInput.Input.Pointer -| Name | Value | Description | -| -------------------------------- | ---- | ------ | -| DEFAULT | 0 | Default | -| EAST | 1 | East arrow | -| WEST | 2 | West arrow | -| SOUTH | 3 | South arrow | -| NORTH | 4 | North arrow | -| WEST_EAST | 5 | West-east arrow | -| NORTH_SOUTH | 6 | North-south arrow | -| NORTH_EAST | 7 | North-east arrow | -| NORTH_WEST | 8 | North-west arrow | -| SOUTH_EAST | 9 | South-east arrow | -| SOUTH_WEST | 10 | South-west arrow | -| NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment| -| NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment| -| CROSS | 13 | Cross (accurate selection) | -| CURSOR_COPY | 14 | Copy cursor | -| CURSOR_FORBID | 15 | Forbid cursor | -| COLOR_SUCKER | 16 | Sucker | -| HAND_GRABBING | 17 | Grabbing hand | -| HAND_OPEN | 18 | Opening hand | -| HAND_POINTING | 19 | Hand-shaped pointer | -| HELP | 20 | Help | -| MOVE | 21 | Move | -| RESIZE_LEFT_RIGHT | 22 | Left and right resizing| -| RESIZE_UP_DOWN | 23 | Up and down resizing| -| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair| -| SCREENSHOT_CURSOR | 25 | Screenshot cursor | -| TEXT_CURSOR | 26 | Text cursor | -| ZOOM_IN | 27 | Zoom in | -| ZOOM_OUT | 28 | Zoom out | -| MIDDLE_BTN_EAST | 29 | Scrolling east | -| MIDDLE_BTN_WEST | 30 | Scrolling west | -| MIDDLE_BTN_SOUTH | 31 | Scrolling south | -| MIDDLE_BTN_NORTH | 32 | Scrolling north | -| MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south | -| MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east | -| MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west | -| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east | -| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west | -| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions| +| Name | Value | Description |Legend| +| -------------------------------- | ---- | ------ |------ | +| DEFAULT | 0 | Default |![Default.png](./figures/Default.png)| +| EAST | 1 | East arrow |![East.png](./figures/East.png)| +| WEST | 2 | West arrow |![West.png](./figures/West.png)| +| SOUTH | 3 | South arrow |![South.png](./figures/South.png)| +| NORTH | 4 | North arrow |![North.png](./figures/North.png)| +| WEST_EAST | 5 | West-east arrow |![West_East.png](./figures/West_East.png)| +| NORTH_SOUTH | 6 | North-south arrow |![North_South.png](./figures/North_South.png)| +| NORTH_EAST | 7 | North-east arrow |![North_East.png](./figures/North_East.png)| +| NORTH_WEST | 8 | North-west arrow |![North_West.png](./figures/North_West.png)| +| SOUTH_EAST | 9 | South-east arrow |![South_East.png](./figures/South_East.png)| +| SOUTH_WEST | 10 | South-west arrow |![South_West.png](./figures/South_West.png)| +| NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment|![North_East_South_West.png](./figures/North_East_South_West.png)| +| NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment|![North_West_South_East.png](./figures/North_West_South_East.png)| +| CROSS | 13 | Cross (accurate selection) |![Cross.png](./figures/Cross.png)| +| CURSOR_COPY | 14 | Copy cursor |![Copy.png](./figures/Copy.png)| +| CURSOR_FORBID | 15 | Forbid cursor |![Forbid.png](./figures/Forbid.png)| +| COLOR_SUCKER | 16 | Sucker |![Colorsucker.png](./figures/Colorsucker.png)| +| HAND_GRABBING | 17 | Grabbing hand |![Hand_Grabbing.png](./figures/Hand_Grabbing.png)| +| HAND_OPEN | 18 | Opening hand |![Hand_Open.png](./figures/Hand_Open.png)| +| HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)| +| HELP | 20 | Help |![Help.png](./figures/Help.png)| +| MOVE | 21 | Move |![Move.png](./figures/Move.png)| +| RESIZE_LEFT_RIGHT | 22 | Left and right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)| +| RESIZE_UP_DOWN | 23 | Up and down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)| +| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)| +| SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)| +| TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)| +| ZOOM_IN | 27 | Zoom in |![Zoom_In.png](./figures/Zoom_In.png)| +| ZOOM_OUT | 28 | Zoom out |![Zoom_Out.png](./figures/Zoom_Out.png)| +| MIDDLE_BTN_EAST | 29 | Scrolling east |![MID_Btn_East.png](./figures/MID_Btn_East.png)| +| MIDDLE_BTN_WEST | 30 | Scrolling west |![MID_Btn_West.png](./figures/MID_Btn_West.png)| +| MIDDLE_BTN_SOUTH | 31 | Scrolling south | ![MID_Btn_South.png](./figures/MID_Btn_South.png) | +| MIDDLE_BTN_NORTH | 32 | Scrolling north |![MID_Btn_North.png](./figures/MID_Btn_North.png)| +| MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south |![MID_Btn_North_South.png](./figures/MID_Btn_North_South.png)| +| MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east |![MID_Btn_North_East.png](./figures/MID_Btn_North_East.png)| +| MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west |![MID_Btn_North_West.png](./figures/MID_Btn_North_West.png)| +| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)| +| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)| +| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)| diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index 7880d8a09af980bbc51635e7220738722142829b..37728bb1823311492718e31b44cd3dd4b63fd4e3 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -3,8 +3,9 @@ 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 provided by this module are system APIs. +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -45,7 +46,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the count value is invalid. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100007 | Service is abnormal. | @@ -95,7 +96,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the count value is invalid. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100007 | Service is abnormal. | @@ -266,7 +267,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | @@ -314,7 +315,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | @@ -369,7 +370,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is not used with | @@ -417,7 +418,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is not used with | @@ -445,7 +446,7 @@ try { ## privacyManager.on -on(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void +on(type: 'activeStateChange', permissionList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void Subscribes to the permission usage status changes of the specified permissions. @@ -458,7 +459,7 @@ Subscribes to the permission usage status changes of the specified permissions. | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| permissionList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in the permission usage.| **Error codes** @@ -467,7 +468,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100004 | The interface is called repeatedly with the same input. | | 12100005 | The registration time has exceeded the limitation. | | 12100007 | Service is abnormal. | @@ -478,9 +479,9 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList = []; +let permissionList = []; try { - privacyManager.on('activeStateChange', permissionNameList, (data) => { + privacyManager.on('activeStateChange', permissionList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -490,7 +491,7 @@ try { ## privacyManager.off -off(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void; +off(type: 'activeStateChange', permissionList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void; Unsubscribes from the permission usage status changes of the specified permissions. @@ -503,7 +504,7 @@ Unsubscribes from the permission usage status changes of the specified permissio | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| permissionList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| **Error codes** @@ -513,7 +514,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | | 12100001 | The parameter is invalid. The permissionName in list is all invalid or the list size is larger than 1024. | -| 12100004 | The interface is not used with | +| 12100004 | The API is not used together with "on()". | | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | @@ -522,9 +523,9 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList = []; +let permissionList = []; try { - privacyManager.off('activeStateChange', permissionNameList); + privacyManager.off('activeStateChange', permissionList); }catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 318ba307995a44950461ae3b9a43e92743c37364..e50764d1b1ff3f948ec123294bb2a013d64329e2 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -18,241 +18,87 @@ import process from '@ohos.process'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| egid | number | Yes| No| Effective group identifier (EGID) of a process.
**System API**: This is a system API.
It is used only to test applications.| -| euid | number | Yes| No| Effective user identifier (EUID) of a process.
**System API**: This is a system API.
It is used only to test applications.| -| gid | number | Yes| No| Group identifier (GID) of a process.
**System API**: This is a system API.
It is used only to test applications.| -| uid | number | Yes| No| User identifier (UID) of a process.| -| groups | number[] | Yes| No| Array with supplementary group IDs.
**System API**: This is a system API.
It is used only to test applications.| -| pid | number | Yes| No| Process ID (PID) of a process.| -| ppid | number | Yes| No| Parent process ID (PPID) of a process.
**System API**: This is a system API.
It is used only to test applications.| -| tid8+ | number | Yes| No| Thread ID (TID) of a process.| +| uid | number | Yes| No| User identifier (UID) of the process.| +| pid | number | Yes| No| Process ID (PID) of the process.| +| tid8+ | number | Yes| No| Thread ID (TID) of the thread.| -## ProcessManager9+ - -Provides APIs for throwing exceptions during the addition of a process. - -### isAppUid9+ - -isAppUid(v: number): boolean - -Checks whether a UID belongs to this application. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| v | number | Yes| UID.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the UID is the application's UID; returns **false** otherwise.| - -**Example** - -```js -let pro = new process.ProcessManager(); -let result = pro.isAppUid(688); -``` - - -### getUidForName9+ - -getUidForName(v: string): number - -Obtains the process UID based on the process name. +## EventListener **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| v | string | Yes| Name of a process.| - -**Return value** - -| Type| Description| +| Name| Description| | -------- | -------- | -| number | Process UID.| - -**Example** - -```js -let pro = new process.ProcessManager(); -let pres = pro .getUidForName("tool"); -``` +| EventListener = (evt:  Object) => void | Event to store.| -### getThreadPriority9+ +## process.isIsolatedProcess8+ -getThreadPriority(v: number): number +isIsolatedProcess(): boolean -Obtains the thread priority based on the specified TID. +Checks whether this process is isolated. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| v | number | Yes| TID.| - **Return value** | Type| Description| | -------- | -------- | -| number | Priority of the thread.| +| boolean | Returns **true** if the process is isolated; returns **false** otherwise.| **Example** ```js -let pro = new process.ProcessManager(); -let tid = process.tid; -let pres = pro.getThreadPriority(tid); +let result = process.isIsolatedProcess(); ``` -### getSystemConfig9+ +## process.is64Bit8+ -getSystemConfig(name: number): number +is64Bit(): boolean -Obtains the system configuration. +Checks whether this process is running in a 64-bit environment. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | number | Yes| System configuration parameter name.| - **Return value** | Type| Description| | -------- | -------- | -| number | System configuration obtained.| - -**Example** - -```js -let pro = new process.ProcessManager(); -let _SC_ARG_MAX = 0; -let pres = pro.getSystemConfig(_SC_ARG_MAX); -``` - - -### getEnvironmentVar9+ - -getEnvironmentVar(name: string): string - -Obtains the value of an environment variable. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Environment variable name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Value of the environment variable.| - -**Example** - -```js -let pro = new process.ProcessManager(); -let pres = pro.getEnvironmentVar("PATH"); -``` - - -### exit9+ - -exit(code: number): void - -Terminates this process. - -Exercise caution when using this API. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| code | number | Yes| Exit code of the process.| +| boolean | Returns **true** if the process is running in a 64-bit environment; returns **false** otherwise.| **Example** ```js -let pro = new process.ProcessManager(); -pro.exit(0); +let result = process.is64Bit(); ``` -### kill9+ +## process.getStartRealtime8+ -kill(signal: number, pid: number): boolean +getStartRealtime(): number -Sends a signal to the specified process to terminate it. +Obtains the duration, in milliseconds, from the time the system starts to the time the process starts. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pid | number | Yes| PID of the process, to which the signal will be sent.| -| signal | number | Yes| Signal to send.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.| +| number | Duration obtained, in millisecond.| **Example** ```js -let pro = new process.ProcessManager(); -let pres = process.pid; -let result = pro.kill(28, pres); +let realtime = process.getStartRealtime(); ``` +## process.getPastCpuTime8+ -## ChildProcess - -Allows a process to obtain the standard input and output of its child processes, send signals, and close its child processes. - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| PID of the child process.
**System API**: This is a system API.
It is used only to test applications.| -| ppid | number | Yes| No| PPID of the child process.
**System API**: This is a system API.
It is used only to test applications.| -| exitCode | number | Yes| No| Exit code of the child process.
**System API**: This is a system API.
It is used only to test applications.| -| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it.
**System API**: This is a system API.
It is used only to test applications.| - - -### wait - -wait(): Promise<number> - -Waits until the child process ends. This method uses a promise to return the exit code of the child process. - -**System API**: This is a system API. +getPastCpuTime(): number -It is used only to test applications. +Obtains the CPU time (in milliseconds) from the time the process starts to the current time. **System capability**: SystemCapability.Utils.Lang @@ -260,57 +106,35 @@ It is used only to test applications. | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the exit code of the child process.| +| number | CPU time obtained, in millisecond.| **Example** ```js -let child = process.runCmd('ls'); -let result = child.wait(); -result.then(val=>{ - console.log("result = " + val); -}) +let result = process.getPastCpuTime() ; ``` -### getOutput - -getOutput(): Promise<Uint8Array> - -Obtains the standard output of the child process. +## process.abort -**System API**: This is a system API. +abort(): void -It is used only to test applications. +Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method. **System capability**: SystemCapability.Utils.Lang -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<Uint8Array> | Promise used to return the standard output in a Uint8Array.| - **Example** ```js -let child = process.runCmd('ls'); -let result = child.wait(); -child.getOutput().then(val=>{ - console.log("child.getOutput = " + val); -}) +process.abort(); ``` -### getErrorOutput - -getErrorOutput(): Promise<Uint8Array> - -Obtains the standard error output of the child process. +## process.uptime -**System API**: This is a system API. +uptime(): number -It is used only to test applications. +Obtains the running time of this process. **System capability**: SystemCapability.Utils.Lang @@ -318,48 +142,24 @@ It is used only to test applications. | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Promise used to return the standard error output in a Uint8Array.| - -**Example** - -```js -let child = process.runCmd('madir test.text'); -let result = child.wait(); -child.getErrorOutput().then(val=>{ - console.log("child.getErrorOutput= " + val); -}) -``` - - -### close - -close(): void - -Closes the child process in running. - -**System API**: This is a system API. - -It is used only to test applications. - -**System capability**: SystemCapability.Utils.Lang +| number | Running time of the process, in seconds.| **Example** ```js -let child = process.runCmd('sleep 5; ls'); -child.close(); +let time = process.uptime(); ``` -### kill - -kill(signal: number | string): void +## process.kill(deprecated) -Sends a signal to the specified child process to terminate it. +kill(signal: number, pid: number): boolean -**System API**: This is a system API. +Sends a signal to the specified process to terminate it. -It is used only to test applications. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [kill9+](#kill9) instead. **System capability**: SystemCapability.Utils.Lang @@ -367,42 +167,34 @@ It is used only to test applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| signal | number \| string | Yes| Number or string to send.| - -**Example** - -```js -let child = process.runCmd('sleep 5; ls'); -child.kill(9); -``` - - -## process.isIsolatedProcess8+ - -isIsolatedProcess(): boolean - -Checks whether this process is isolated. - -**System capability**: SystemCapability.Utils.Lang +| pid | number | Yes| PID of the process, to which the signal will be sent.| +| signal | number | Yes| Signal to send.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the process is isolated; returns **false** otherwise.| +| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.| **Example** ```js -let result = process.isIsolatedProcess(); +let pres = process.pid +let result = process.kill(28, pres) ``` -## process.isAppUid8+ +## process.exit(deprecated) -isAppUid(v: number): boolean +exit(code: number): void -Checks whether a UID belongs to this application. +Terminates this process. + +Exercise caution when using this API. After this API is called, the application exits. If the input parameter is not 0, data loss or exceptions may occur. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [exit9+](#exit9) instead. **System capability**: SystemCapability.Utils.Lang @@ -410,48 +202,25 @@ Checks whether a UID belongs to this application. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| v | number | Yes| UID.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the UID is the application's UID; returns **false** otherwise.| - -**Example** - -```js -let result = process.isAppUid(688); -``` - - -## process.is64Bit8+ - -is64Bit(): boolean - -Checks whether this process is running in a 64-bit environment. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the process is running in a 64-bit environment; returns **false** otherwise.| +| code | number | Yes| Exit code of the process.| **Example** ```js -let result = process.is64Bit(); +process.exit(0); ``` -## process.getUidForName8+ +## process.getUidForName(deprecated) getUidForName(v: string): number Obtains the process UID based on the process name. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUidForName9+](#getuidforname9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -473,12 +242,16 @@ let pres = process.getUidForName("tool") ``` -## process.getThreadPriority8+ +## process.getThreadPriority(deprecated) getThreadPriority(v: number): number Obtains the thread priority based on the specified TID. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getThreadPriority9+](#getthreadpriority9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -501,53 +274,47 @@ let pres = process.getThreadPriority(tid); ``` -## process.getStartRealtime8+ - -getStartRealtime(): number +## process.isAppUid(deprecated) -Obtains the duration, in milliseconds, from the time the system starts to the time the process starts. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Duration obtained.| - -**Example** +isAppUid(v: number): boolean -```js -let realtime = process.getStartRealtime(); -``` +Checks whether a UID belongs to this application. -## process.getPastCpuTime8+ +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isAppUid9+](#isappuid9) instead. -getPastCpuTime(): number +**System capability**: SystemCapability.Utils.Lang -Obtains the CPU time (in milliseconds) from the time the process starts to the current time. +**Parameters** -**System capability**: SystemCapability.Utils.Lang +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| v | number | Yes| UID.| **Return value** | Type| Description| | -------- | -------- | -| number | CPU time obtained.| +| boolean | Returns **true** if the UID belongs to the application; returns **false** otherwise.| **Example** ```js -let result = process.getPastCpuTime() ; +let result = process.isAppUid(688); ``` -## process.getSystemConfig8+ +## process.getSystemConfig(deprecated) getSystemConfig(name: number): number Obtains the system configuration. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSystemConfig9+](#getsystemconfig9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -570,12 +337,16 @@ let pres = process.getSystemConfig(_SC_ARG_MAX) ``` -## process.getEnvironmentVar8+ +## process.getEnvironmentVar(deprecated) getEnvironmentVar(name: string): string Obtains the value of an environment variable. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEnvironmentVar9+](#getenvironmentvar9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -597,15 +368,17 @@ let pres = process.getEnvironmentVar("PATH") ``` -## process.runCmd +## ProcessManager9+ -runCmd(command: string, options?: { timeout?: number, killSignal?: number | string, maxBuffer?: number }): ChildProcess +Provides APIs for throwing exceptions during the addition of a process. -Forks a new process to run a shell command and returns the **ChildProcess** object. +A **ProcessManager** object is obtained through its own constructor. -**System API**: This is a system API. +### isAppUid9+ -It is used only to test applications. +isAppUid(v: number): boolean + +Checks whether a UID belongs to this application. **System capability**: SystemCapability.Utils.Lang @@ -613,58 +386,27 @@ It is used only to test applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| command | string | Yes| Shell command to run.| -| options | Object | No| Related parameters.| - -**Table 1** options - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| -| maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| +| v | number | Yes| UID.| **Return value** | Type| Description| | -------- | -------- | -| [ChildProcess](#childprocess) | **ChildProcess** object.| +| boolean | Returns **true** if the UID belongs to the application; returns **false** otherwise.| **Example** ```js -let child = process.runCmd('ls', { maxBuffer : 2 }); -let result = child.wait(); -child.getOutput.then(val=>{ - console.log("child.getOutput = " + val); -}) -``` - - -## process.abort - -abort(): void - -Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method. - -**System capability**: SystemCapability.Utils.Lang - -**Example** - -```js -process.abort(); +let pro = new process.ProcessManager(); +let result = pro.isAppUid(688); ``` -## process.on - -on(type: string, listener: EventListener): void - -Stores the events triggered by the user. +### getUidForName9+ -**System API**: This is a system API. +getUidForName(v: string): number -It is used only to test applications. +Obtains the process UID based on the process name. **System capability**: SystemCapability.Utils.Lang @@ -672,33 +414,27 @@ It is used only to test applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the events to store. | -| listener | EventListener | Yes| Callback invoked to return the event.| +| v | string | Yes| Name of a process.| -**Table 2** EventListener +**Return value** -| Name| Description| +| Type| Description| | -------- | -------- | -| EventListener = (evt:  Object) => void | Event to store.| +| number | Process UID.| **Example** ```js -process.on("data", (e)=>{ - console.log("data callback"); -}) +let pro = new process.ProcessManager(); +let pres = pro .getUidForName("tool"); ``` -## process.off - -off(type: string): boolean - -Deletes the event stored by the user. +### getThreadPriority9+ -**System API**: This is a system API. +getThreadPriority(v: number): number -It is used only to test applications. +Obtains the thread priority based on the specified TID. **System capability**: SystemCapability.Utils.Lang @@ -706,31 +442,28 @@ It is used only to test applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to delete.| +| v | number | Yes| TID.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the event is deleted; returns **false** otherwise.| +| number | Priority of the thread.| **Example** ```js -process.on("data", (e)=>{ - console.log("data callback"); -}) -let result = process.off("data"); +let pro = new process.ProcessManager(); +let tid = process.tid; +let pres = pro.getThreadPriority(tid); ``` -## process.exit - -exit(code: number): void +### getSystemConfig9+ -Terminates this process. +getSystemConfig(name: number): number -Exercise caution when using this API. +Obtains the system configuration. **System capability**: SystemCapability.Utils.Lang @@ -738,43 +471,28 @@ Exercise caution when using this API. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| code | number | Yes| Exit code of the process.| - -**Example** - -```js -process.exit(0); -``` - - -## process.cwd - -cwd(): string - -Obtains the working directory of this process. - -**System API**: This is a system API. +| name | number | Yes| System configuration parameter name.| -It is used only to test applications. +**Return value** -**System capability**: SystemCapability.Utils.Lang +| Type| Description| +| -------- | -------- | +| number | System configuration obtained.| **Example** ```js -let path = process.cwd(); +let pro = new process.ProcessManager(); +let _SC_ARG_MAX = 0; +let pres = pro.getSystemConfig(_SC_ARG_MAX); ``` -## process.chdir - -chdir(dir: string): void - -Changes the working directory of this process. +### getEnvironmentVar9+ -**System API**: This is a system API. +getEnvironmentVar(name: string): string -It is used only to test applications. +Obtains the value of an environment variable. **System capability**: SystemCapability.Utils.Lang @@ -782,37 +500,47 @@ It is used only to test applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| dir | string | Yes| Path| +| name | string | Yes| Environment variable name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Value of the environment variable.| **Example** ```js -process.chdir('/system'); +let pro = new process.ProcessManager(); +let pres = pro.getEnvironmentVar("PATH"); ``` -## process.uptime +### exit9+ -uptime(): number +exit(code: number): void -Obtains the running time of this process. +Terminates this process. + +Exercise caution when using this API. After this API is called, the application exits. If the input parameter is not 0, data loss or exceptions may occur. **System capability**: SystemCapability.Utils.Lang -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| number | Running time of the process, in seconds.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| code | number | Yes| Exit code of the process.| **Example** ```js -let time = process.uptime(); +let pro = new process.ProcessManager(); +pro.exit(0); ``` -## process.kill +### kill9+ kill(signal: number, pid: number): boolean @@ -836,6 +564,7 @@ Sends a signal to the specified process to terminate it. **Example** ```js -let pres = process.pid -let result = process.kill(28, pres) +let pro = new process.ProcessManager(); +let pres = process.pid; +let result = pro.kill(28, pres); ``` diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 24d70e98a4d97f58acbf6f4089b36d2b628d304b..e7b196f4a330be1c694a46c04669a307f83769da 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -45,11 +45,11 @@ Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. | +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. | ## prompt.showDialog @@ -146,11 +146,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| title | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | -| message | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | -| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| title | string | No | Title of the dialog box. | +| message | string | No | Text body. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -257,7 +257,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| title | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | +| title | string | No | Title of the text to display. | | buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -276,7 +276,7 @@ Describes the menu item button in the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ----- | ---------------------------------------- | ---- | ------- | -| text | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Button text.| -| color | string \| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text color of the button.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | -------------- | +| text | string | Yes | Button text.| +| color | string | Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index e004b48719c7204e420ba9acb40580907c09b6ec..1df1b8d7dd61ca1c5a92b65c1557aed3697a36e0 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -10,7 +10,7 @@ The **radio** module provides basic network search management functions. You can ## Modules to Import ``` -import radio from '@ohos.telephony.radio' +import radio from '@ohos.telephony.radio'; ``` ## radio.getRadioTech @@ -45,7 +45,7 @@ Obtains the RAT used in the CS and PS domains for the SIM card in the specified ```js let slotId = 0; -radio.getRadioTech(slotId, (err, data) =>{ +radio.getRadioTech(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -127,7 +127,7 @@ Obtains the network status. This API uses an asynchronous callback to return the **Example** ```js -radio.getNetworkState((err, data) =>{ +radio.getNetworkState((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2464,7 +2464,7 @@ Defines the signal strength. | --------------- | --------------------------- | ---- | ------------------ | | signalType | [NetworkType](#networktype) | Yes | Signal strength type.| | signalLevel | number | Yes | Signal strength level.| -| dBm9+| number | Yes | Network signal strength. | +| dBm9+| number | Yes | Signal strength, in dBm. | ## NetworkType diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index f443c028e40072e8b402f93b54be1e9ecfdc0842..7d56973be54adf176ce6c22519cb125079f19df3 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgentManager (Reminder Agent Management) +# @ohos.reminderAgentManager (reminderAgentManager) The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. @@ -696,8 +696,8 @@ Sets the time information for a calendar reminder. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | year | number | Yes| Year.| -| month | number | Yes| Month.| -| day | number | Yes| Date.| -| hour | number | Yes| Hour.| -| minute | number | Yes| Minute.| -| second | number | No| Second.| +| month | number | Yes| Month. The value ranges from 1 to 12.| +| day | number | Yes| Day. The value ranges from 1 to 31.| +| hour | number | Yes| Hour. The value ranges from 0 to 23.| +| minute | number | Yes| Minute. The value ranges from 0 to 59.| +| second | number | No| Second. The value ranges from 0 to 59.| diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 7dc343709c19421175b4f99e6308c1c0ad90e5dd..41d18e140d9442384c32d7ccbd94ccc153b8ca07 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -13,14 +13,15 @@ The Resource Manager module provides APIs to obtain information about applicatio import resourceManager from '@ohos.resourceManager'; ``` -## Instruction +## How to Use -Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. -For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. +For details about how to reference context in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). ```ts -import Ability from '@ohos.application.Ability'; -class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let context = this.context; let resourceManager = context.resourceManager; @@ -60,6 +61,7 @@ Obtains the **ResourceManager** object of this application. This API uses an asy }); }); ``` +> **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. ## resourceManager.getResourceManager @@ -76,7 +78,7 @@ Obtains the **ResourceManager** object of an application based on the specified | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of the target application. | | callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.| **Example** @@ -116,6 +118,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom console.log("error is " + error); }); ``` +> **NOTE**
> In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. ## resourceManager.getResourceManager @@ -132,7 +135,7 @@ Obtains the **ResourceManager** object of an application based on the specified | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of the target application.| **Return value** @@ -168,12 +171,12 @@ Enumerates the device types. | Name | Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -275,7 +278,7 @@ Defines the capability of accessing application resources. > **NOTE** > -> - The APIs involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. +> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. @@ -642,7 +645,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -1655,7 +1658,7 @@ Obtains the string corresponding to the specified resource name. This API uses a | Type | Description | | --------------------- | ---------- | -| Promise<string> | String corresponding to the resource name.| +| Promise<string> | Promise used to return the result.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2033,7 +2036,7 @@ Obtains the string corresponding to the specified resource ID. This API returns | Type | Description | | ------ | ----------- | -| string | Promise used to return the result.| +| string | String corresponding to the specified resource ID.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2072,7 +2075,7 @@ Obtains the string corresponding to the specified resource object. This API retu | Type | Description | | ------ | ---------------- | -| string | Promise used to return the result.| +| string | String corresponding to the resource object.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2116,7 +2119,7 @@ Obtains the string corresponding to the specified resource name. This API return | Type | Description | | ------ | ---------- | -| string | String corresponding to the specified resource name.| +| string | String corresponding to the resource name.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2527,7 +2530,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead. diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index bec171f5b45400827b3e76e79226b1b4210569d2..cf918a571c7121bdb5b9c5f51cb7a93ce782968d 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -233,7 +233,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -311,7 +311,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -388,7 +388,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -444,7 +444,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index ce6daa95dc50c55f328eec71d8911f5024a2e6b7..01fa04dc18f59bf47d49248681d5f46fba32d187 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -54,9 +54,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | @@ -105,9 +105,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | @@ -133,6 +133,8 @@ Queries the group of this application. This API uses a promise to return the res **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API. + **Return value** | Type | Description | @@ -145,9 +147,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000005 | Application is not installed. | | 10000006 | Failed to get the application information. | @@ -175,6 +177,8 @@ Queries the group of this application. This API uses an asynchronous callback to **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -186,10 +190,10 @@ Queries the group of this application. This API uses an asynchronous callback to For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000005 | Application is not installed. | | 10000006 | Failed to get the application information. | @@ -236,10 +240,10 @@ Queries the application usage duration statistics based on the specified start t For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -296,10 +300,10 @@ Queries the application usage duration statistics based on the specified start t For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -350,10 +354,10 @@ Queries the application usage duration statistics in the specified time frame at For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -409,10 +413,10 @@ Queries the application usage duration statistics in the specified time frame at For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -461,9 +465,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -519,9 +523,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -552,6 +556,8 @@ Queries events of this application based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -565,10 +571,10 @@ Queries events of this application based on the specified start time and end tim For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -601,6 +607,8 @@ Queries events of this application based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -619,10 +627,10 @@ Queries events of this application based on the specified start time and end tim For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -668,10 +676,10 @@ Queries FA usage records. This API uses a promise to return a maximum of 1000 FA For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -718,10 +726,10 @@ Queries FA usage records. This API uses an asynchronous callback to return a max For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -776,9 +784,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -826,9 +834,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -883,11 +891,11 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | -| 10000005 | Application is not installed. | +| 10000005 | Application is not installed. | | 10000006 | Failed to get the application information. | | 10100002 | Failed to get the application group information. | @@ -932,11 +940,11 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | -| 10000005 | Application is not installed. | +| 10000005 | Application is not installed. | | 10000006 | Failed to get the application information. | | 10100002 | Failed to get the application group information. | @@ -982,9 +990,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10100001 | Repeated operation on the application group. | @@ -1037,10 +1045,10 @@ Sets a group for the application specified by **bundleName**. This API uses an a For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10100001 | Repeated operation on the application group. | @@ -1088,9 +1096,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10100001 | Repeated operation on the application group. | @@ -1147,9 +1155,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10100001 | Repeated operation on the application group. | @@ -1202,10 +1210,10 @@ Deregisters the callback for application group changes. This API uses a promise For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10100001 | Repeated operation on the application group. | @@ -1246,10 +1254,10 @@ Deregisters the callback for application group changes. This API uses an asynchr For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10100001 | Repeated operation on the application group. | @@ -1299,10 +1307,10 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -1348,9 +1356,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -1403,9 +1411,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | ID | Error Message | | ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -1450,10 +1458,10 @@ Queries the number of notifications from all applications based on the specified For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md). | ID | Error Message | -| ---------- | ---------------------------- | -| 10000001 | Memory operation failed. | -| 10000002 | Parcel operation failed. | -| 10000003 | System service operation failed. | +| ---------- | ---------------------------- | +| 10000001 | Memory operation failed. | +| 10000002 | Parcel operation failed. | +| 10000003 | System service operation failed. | | 10000004 | IPC failed. | | 10000006 | Failed to get the application information. | | 10000007 | Failed to get the system time. | @@ -1558,6 +1566,8 @@ Provides information about an application event. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API. + | Name | Type | Mandatory | Description | | --------------------- | ------ | ---- | ---------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 0e7ad7e7c38f32e85af6ab3504252da38afb32eb..5ba1e47b2f1d702e226ec3359044309b44a7dacb 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -346,6 +346,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes | 9700001 | Memory operation failed. | | 9700002 | Parcel operation failed. | | 9700003 | System service operation failed. | +| 9700004 | Checking workInfo failed. | **Example** @@ -391,6 +392,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes | 9700001 | Memory operation failed. | | 9700002 | Parcel operation failed. | | 9700003 | System service operation failed. | +| 9700004 | Checking workInfo failed. | **Example** @@ -430,7 +432,7 @@ Provides detailed information about the task. For details about the constraints | isPersisted | boolean | No | Whether to enable persistent storage for the task. | | isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | | idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: any} | No | Carried parameters. | +| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. | ## NetworkType Enumerates the network types that can trigger the task. diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index b5cbbd52e0c0bc4cc2f9cd364b679bc02f989f85..9f7933724c12285f56ac130c9c49c51f7e3549e4 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -362,7 +362,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 200002 | if the uri is not exist. | **Example** @@ -598,7 +598,7 @@ export default { // detail page export default { onInit() { - console.info('showData1:' + router.getParams()[data1]); + console.info('showData1:' + router.getParams()['data1']); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index bddad259f782ca6ece549da06ab6ae4e69bbc441..e25ca6bcb1381a41f8491fcb8c50b2e65e5929e1 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -482,7 +482,7 @@ Enumerates the types of **RunningLock** objects. **System capability:** SystemCapability.PowerManager.PowerManager.Core -| Name | Value | Description | -| ------------------------ | ---- | -------------------------------------- | -| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | -| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| +| Name | Value | Description | +| --------------------------------- | ---- | ------------------------------------------------------------ | +| BACKGROUND(deprecated) | 1 | A lock that prevents the system from hibernating when the screen is off.
**NOTE**
This parameter is supported since API version 7 and deprecated since API version 10.| +| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen. | diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index f7f2a551648df0db4ad96733ef1a169f8fb42e14..2ee3029a1f51022c1ce7bf39fddfe9288ec45e11 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,4 +1,4 @@ -# @ohos.screenLock (Screenlock) +# @ohos.screenLock (Screen Lock) The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. @@ -12,12 +12,14 @@ The **screenlock** module is a system module in OpenHarmony. It provides APIs fo import screenlock from '@ohos.screenLock'; ``` -## EventType +## EventType9+ Defines the system event type. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + | Event Type | Description | | ------------------ | ------------------------ | | beginWakeUp | Wakeup starts.| @@ -35,15 +37,17 @@ Defines the system event type. | screenlockEnabled | Screen lock is enabled. | | serviceRestart | The screen lock service is restarted. | -## SystemEvent +## SystemEvent9+ Defines the structure of the system event callback. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | -| eventType | [EventType](#eventtype) | Yes | System event type.| +| eventType | [EventType](#eventtype9) | Yes | System event type.| | params | string | Yes | System event parameters.| ## screenlock.isLocked9+ @@ -54,6 +58,8 @@ Checks whether the screen is locked. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + **Return value** | Type | Description | @@ -66,26 +72,6 @@ Checks whether the screen is locked. let isLocked = screenlock.isLocked(); ``` -## screenlock.isSecure9+ - -isSecure(): boolean - -Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. - -**System capability**: SystemCapability.MiscServices.ScreenLock - -**Return value** - -| Type | Description | -| ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if the device is in secure mode; returns **false** otherwise.| - -**Example** - -```js -let isSecure = screenlock.isSecure(); -``` - ## screenlock.unlock9+ unlock(callback: AsyncCallback<boolean>): void @@ -94,6 +80,8 @@ Unlocks the screen. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -128,6 +116,8 @@ Unlocks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + **Return value** | Type | Description | @@ -236,7 +226,7 @@ Registers a callback for system events related to screen locking. This API can b | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------- | -| callback | Callback\<[SystemEvent](#systemevent)> | Yes | Callback for system events related to screen locking.| +| callback | Callback\<[SystemEvent](#systemevent9)> | Yes | Callback for system events related to screen locking.| **Return value** @@ -266,7 +256,7 @@ try { ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: string, parameter: number, callback: AsyncCallback<boolean>): void +sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback<boolean>): void Sends an event to the screen lock service. This API uses an asynchronous callback to return the result. @@ -278,7 +268,7 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | --------- | ------------------------ | ---- | -------------------- | -| event | string | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| +| event | String | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| | parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| | callback | AsyncCallback\ | Yes | Callback used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite. | @@ -304,7 +294,7 @@ screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: string, parameter: number): Promise<boolean> +sendScreenLockEvent(event: String, parameter: number): Promise<boolean> Sends an event to the screen lock service. This API uses a promise to return the result. @@ -316,7 +306,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.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| +| event | String | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| | parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| **Return value** @@ -343,7 +333,7 @@ Checks whether the screen is locked. This API uses an asynchronous callback to r > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -373,7 +363,7 @@ Checks whether the screen is locked. This API uses a promise to return the resul > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -401,7 +391,7 @@ Checks whether the device is in secure mode. When the device is in secure mode, > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -431,7 +421,7 @@ Checks whether the device is in secure mode. When the device is in secure mode, > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -458,7 +448,7 @@ Unlocks the screen. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock9+](#screenlockunlock9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -488,7 +478,7 @@ Unlocks the screen. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock9+](#screenlockunlock9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.ScreenLock diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 309a1bc64491497bf61aaf6f2695a9d5c4fbd9d4..8b760e7cb48b3031e728ec80cc2c178501abb677 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -37,10 +37,10 @@ Describes the region of the screen to capture. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| left | number | Yes | Left boundary of the screen region to capture.| -| top | number | Yes | Top boundary of the screen region to capture.| -| width | number | Yes | Width of the screen region to capture.| -| height | number | Yes | Height of the screen region to capture.| +| left | number | Yes | Left boundary of the screen region to capture, in pixels.| +| top | number | Yes | Top boundary of the screen region to capture, in pixels.| +| width | number | Yes | Width of the screen region to capture, in pixels.| +| height | number | Yes | Height of the screen region to capture, in pixels.| ## Size @@ -51,8 +51,8 @@ Describes the size of the screen region to capture. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| width | number | Yes | Width of the screen region to capture.| -| height | number | Yes | Height of the screen region to capture.| +| width | number | Yes | Width of the screen region to capture, in pixels.| +| height | number | Yes | Height of the screen region to capture, in pixels.| ## screenshot.save diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 987da3a5c044ee43e963df6a1ef731d8a0d07915..e0438820b47438b2fa545723003edc91b7eef3f5 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -2661,7 +2661,7 @@ try { ## sensor.getAngleVariation9+ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, - callback: AsyncCallback): void + callback: AsyncCallback<Array<number>>): void Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. @@ -2717,7 +2717,7 @@ try { ## sensor.getAngleVariation9+ -getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise +getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> Obtains the angle change between two rotation matrices. This API uses a promise to return the result. @@ -2777,7 +2777,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void +getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void Obtains the rotation matrix from a rotation vector. This API uses an asynchronous callback to return the result. @@ -2819,7 +2819,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(rotationVector: Array<number>): Promise +getRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> Obtains the rotation matrix from a rotation vector. This API uses a promise to return the result. @@ -2866,7 +2866,7 @@ try { ## sensor.transformRotationMatrix9+ transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, - callback: AsyncCallback): void + callback: AsyncCallback<Array<number>>): void Transforms a rotation vector based on the coordinate system. This API uses an asynchronous callback to return the result. @@ -2913,7 +2913,7 @@ try { ## sensor.transformRotationMatrix9+ -transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> Transforms a rotation vector based on the coordinate system. This API uses a promise to return the result. @@ -2964,7 +2964,7 @@ try { ## sensor.getQuaternion9+ -getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void +getQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void Obtains the quaternion from a rotation vector. This API uses an asynchronous callback to return the result. @@ -3006,7 +3006,7 @@ try { ## sensor.getQuaternion9+ -getQuaternion(rotationVector: Array<number>): Promise +getQuaternion(rotationVector: Array<number>): Promise<Array<number>> Obtains the quaternion from a rotation vector. This API uses a promise to return the result. @@ -3052,7 +3052,7 @@ try { ## sensor.getOrientation9+ -getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void +getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. @@ -3101,7 +3101,7 @@ try { ## sensor.getOrientation9+ -getOrientation(rotationMatrix: Array<number>): Promise +getOrientation(rotationMatrix: Array<number>): Promise<Array<number>> Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. @@ -3193,7 +3193,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>): Promise<RotationMatrixResponse> Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses a promise to return the result. @@ -3239,7 +3239,7 @@ try { ## sensor.getSensorList9+ -getSensorList(callback: AsyncCallback): void +getSensorList(callback: AsyncCallback<Array<Sensor>>): void Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. @@ -3249,7 +3249,7 @@ Obtains information about all sensors on the device. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | Yes | Callback used to return the sensor list.| +| callback | AsyncCallback<Array<[Sensor](#sensor9)>> | Yes | Callback used to return the sensor list.| **Error code** @@ -3279,7 +3279,7 @@ try { ## sensor.getSensorList9+ - getSensorList(): Promise< Array<Sensor>> + getSensorList(): Promise<Array<Sensor>> Obtains information about all sensors on the device. This API uses a promise to return the result. @@ -3289,7 +3289,7 @@ Obtains information about all sensors on the device. This API uses a promise to | Name | Type | Mandatory| Description | | ------- | ---------------------------------------- | ---- | ---------------- | -| promise | Promise | Yes | Promise used to return the sensor list.| +| promise | Promise<Array<[Sensor](#sensor9)>> | Yes | Promise used to return the sensor list.| **Error code** @@ -3831,18 +3831,6 @@ Describes the geographical location. | longitude | number | Yes | Yes | Longitude. | | altitude | number | Yes | Yes | Altitude.| -## LocationOptions - -Describes the geographical location. - -**System capability**: SystemCapability.Sensors.Sensor - -| Name | Type | Readable | Writable | Description | -| --------- | ------ | -------- | -------- | ----------- | -| latitude | number | Yes | Yes | Latitude. | -| longitude | number | Yes | Yes | Longitude. | -| altitude | number | Yes | Yes | Altitude. | - ## sensor.on(deprecated) ### ACCELEROMETER(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 0c0243c3dbe85939b1da5623baac1b3137926e15..f8d5e0d75a5425fcade12cd6f8f90e8cc5ee720a 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# @ohos.telephony.sim (SIM Management) +# @ohos.telephony.sim (SIM) -The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > @@ -121,7 +121,7 @@ promise.then(data => { hasOperatorPrivileges(slotId: number, callback: AsyncCallback\): void -Checks whether the application (caller) has been granted the operator permission. This API uses an asynchronous callback to return the result. +Checks whether the application (caller) has been granted the operator permission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -132,6 +132,17 @@ Checks whether the application (caller) has been granted the operator permission | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -144,7 +155,7 @@ sim.hasOperatorPrivileges(0, (err, data) => { hasOperatorPrivileges(slotId: number): Promise -Checks whether the application (caller) has been granted the carrier permission. This API uses a promise to return the result. +Checks whether the application (caller) has been granted the operator permission. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -160,6 +171,17 @@ Checks whether the application (caller) has been granted the carrier permission. | :----------------- | :---------------------------------------------------------- | | Promise\ | Promise used to return the result. The value **true** indicates that the application (caller) has been granted the carrier permission, and the value **false** indicates the opposite.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -184,7 +206,18 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ---------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result. which is an ISO country code, for example, **CN** (China).| +| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an ISO country code, for example, **CN** (China).| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | **Example** @@ -215,6 +248,17 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use | ----------------- | ------------------------------------------------------------ | | Promise\ | Promise used to return the result, which is an ISO country code, for example, **CN** (China).| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -231,7 +275,7 @@ promise.then(data => { getSimOperatorNumeric\(slotId: number, callback: AsyncCallback\): void -Obtains the public land mobile network (PLMN) ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the public land mobile network \(PLMN\) ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -242,6 +286,17 @@ Obtains the public land mobile network (PLMN) ID of the SIM card in the specifie | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -271,6 +326,17 @@ Obtains the PLMN ID of the SIM card in the specified slot. This API uses a promi | ----------------- | ------------------------------------------------ | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -287,7 +353,7 @@ promise.then(data => { getSimSpn\(slotId: number, callback: AsyncCallback\): void -Obtains the service provider name (SPN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the service provider name (SPN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -298,6 +364,17 @@ Obtains the service provider name (SPN) of the SIM card in the specified slot. T | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -311,7 +388,7 @@ sim.getSimSpn(0, (err, data) => { getSimSpn\(slotId: number\): Promise -Obtains the SPN of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the SPN of the SIM card in the specified slot. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -327,6 +404,17 @@ Obtains the SPN of the SIM card in the specified slot. This API uses a promise t | ----------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -343,7 +431,7 @@ promise.then(data => { getSimState\(slotId: number, callback: AsyncCallback\): void -Obtains the status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the state of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -354,6 +442,17 @@ Obtains the status of the SIM card in the specified slot. This API uses an async | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\<[SimState](#simstate)\> | Yes | Callback used to return the result. For details, see [SimState](#simstate). | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -367,7 +466,7 @@ sim.getSimState(0, (err, data) => { getSimState\(slotId: number\): Promise -Obtains the status of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the state of the SIM card in the specified slot. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -383,6 +482,17 @@ Obtains the status of the SIM card in the specified slot. This API uses a promis | -------------------------------- | ------------------------------------------ | | Promise\<[SimState](#simstate)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -409,6 +519,17 @@ Obtains the type of the SIM card in the specified slot. This API uses an asynchr | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\<[CardType](#cardtype7)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -438,6 +559,17 @@ Obtains the type of the SIM card in the specified slot. This API uses a promise | ----------------- | ------------------------------------------------------------ | | Promise\<[CardType](#cardtype7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -465,6 +597,17 @@ Checks whether the SIM card in the specified slot is installed. This API uses an | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -494,6 +637,17 @@ Checks whether the SIM card in the specified slot is installed. This API uses a | --------------------- | ---------------------------------- | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the SIM card in the specified slot is installed, and the value **false** indicates the opposite.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -509,7 +663,7 @@ promise.then(data => { getSimAccountInfo(slotId: number, callback: AsyncCallback): void -Obtains account information of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains SIM card account information. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -524,6 +678,19 @@ Obtains account information of the SIM card in the specified slot. This API uses | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\<[IccAccountInfo](#iccaccountinfo7)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -537,7 +704,7 @@ sim.getSimAccountInfo(0, (err, data) => { getSimAccountInfo(slotId: number): Promise -Obtains account information of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains SIM card account information. This API uses a promise to return the result. **System API**: This is a system API. @@ -557,6 +724,19 @@ Obtains account information of the SIM card in the specified slot. This API uses | -------------------------------------------- | ------------------------------------------ | | Promise<[IccAccountInfo](#iccaccountinfo7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -586,6 +766,18 @@ Obtains the account information list of the active SIM card. This API uses an as | -------- | ----------------------------------------------------------- | ---- | ---------- | | callback | AsyncCallback\\> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -613,6 +805,18 @@ Obtains the account information list of the active SIM card. This API uses a pro | ---------------------------------------------------- | ---------------------------------------------- | | Promise\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -643,6 +847,19 @@ Sets the default slot ID of the SIM card that provides voice services. This API | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301001 | SIM card is not activated. | + **Example** ```js @@ -676,6 +893,19 @@ Sets the default slot ID of the SIM card that provides voice services. This API | --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301001 | SIM card is not activated. | + **Example** ```js @@ -707,6 +937,18 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy | name | string | Yes | SIM card name. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -741,6 +983,18 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom | --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -772,6 +1026,18 @@ Obtains the name of the SIM card in the specified slot. This API uses an asynchr | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<string> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -805,6 +1071,18 @@ Obtains the name of the SIM card in the specified slot. This API uses a promise | --------------------- | -------------------------------------- | | Promise<string> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -836,6 +1114,18 @@ Sets a display number for the SIM card in the specified slot. This API uses an a | number | string | Yes | SIM card number. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -871,6 +1161,18 @@ Sets a display number for the SIM card in the specified slot. This API uses a pr | -------------- | ------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -902,6 +1204,18 @@ Obtains the display number of the SIM card in the specified slot. This API uses | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<string> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -935,6 +1249,18 @@ Obtains the display number of the SIM card in the specified slot. This API uses | --------------------- | --------------------------------- | | Promise<string> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -950,7 +1276,7 @@ promise.then(data => { activateSim(slotId: number, callback: AsyncCallback): void -Activates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Activates a SIM card in a specified card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -965,6 +1291,18 @@ Activates the SIM card in the specified slot. This API uses an asynchronous call | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -998,6 +1336,18 @@ Activates the SIM card in the specified slot. This API uses a promise to return | --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1013,7 +1363,7 @@ promise.then(data => { deactivateSim(slotId: number, callback: AsyncCallback): void -Deactivates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Disables the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1028,6 +1378,18 @@ Deactivates the SIM card in the specified slot. This API uses an asynchronous ca | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1041,7 +1403,7 @@ sim.deactivateSim(0, (err, data) => { deactivateSim(slotId: number): Promise\ -Deactivates the SIM card in the specified slot. This API uses a promise to return the result. +Disables the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -1061,6 +1423,18 @@ Deactivates the SIM card in the specified slot. This API uses a promise to retur | --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1090,7 +1464,20 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- lockType: [LockType](#locktype8)
- password: string
- state: [LockState](#lockstate8) | + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | **Example** @@ -1123,7 +1510,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- lockType: [LockType](#locktype8)
- password: string
- state: [LockState](#lockstate8) | **Return value** @@ -1131,6 +1518,19 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom | ---------------------------------------------------- | -------------------------------------------- | | Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1167,6 +1567,19 @@ Obtains the lock status of the SIM card in the specified slot. This API uses an | callback | AsyncCallback\<[LockState](#lockstate8)\> | Yes | Callback used to return the result. | | options | [LockType](#locktype8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN 2 lock| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1201,6 +1614,19 @@ Obtains the lock status of the SIM card in the specified slot. This API uses a p | ---------------------------------- | -------------------------------------------- | | Promise<[LockState](#lockstate8)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1233,6 +1659,19 @@ Changes the PIN of the SIM card in the specified slot. This API uses an asynchro | newPin | string | Yes | New PIN. | | oldPin | string | Yes | Old PIN. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1268,6 +1707,19 @@ Changes the PIN of the SIM card in the specified slot. This API uses a promise t | ---------------------------------------------------- | --------------------------------------------- | | Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1300,6 +1752,19 @@ Changes PIN 2 of the SIM card in the specified slot. This API uses an asynchrono | newPin2 | string | Yes | New PIN. | | oldPin2 | string | Yes | Old PIN. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1335,6 +1800,19 @@ Changes PIN 2 of the SIM card in the specified slot. This API uses a promise to | ---------------------------------------------------- | --------------------------------------------- | | Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1350,7 +1828,7 @@ promise.then(data => { unlockPin(slotId: number, pin: string, callback: AsyncCallback): void -Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1366,6 +1844,19 @@ Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous | pin | string | Yes | PIN of the SIM card. | | callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1401,6 +1892,19 @@ Unlocks the PIN of the SIM card in the specified slot. This API uses a promise t | ---------------------------------------------------- | -------------------------------------------------- | | Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1415,7 +1919,7 @@ promise.then(data => { ## sim.unlockPuk7+ -unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback): void +unlockPuk(slotId: number, newPin: string, puk: string, callback: AsyncCallback): void Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1434,6 +1938,19 @@ Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchro | puk | string | Yes | PUK of the SIM card. | | callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1471,6 +1988,19 @@ Unlocks the PUK of the SIM card in the specified slot. This API uses a promise t | ---------------------------------------------------- | -------------------------------------------------- | | Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1501,9 +2031,22 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN 2 of the SIM card. | +| pin2 | string | Yes | PIN of the SIM card. | | callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1531,7 +2074,7 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN 2 of the SIM card. | +| pin2 | string | Yes | PIN of the SIM card. | **Return value** @@ -1539,6 +2082,19 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to | ----------------------------------------------------- | -------------------------------------------------- | | Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1569,9 +2125,22 @@ Unlocks PUK 2 of the SIM card in the specified slot. This API uses an asynchrono | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | newPin2 | string | Yes | New PIN 2. | -| puk2 | string | Yes | PUK 2 of the SIM card. | +| puk2 | string | Yes | PUK of the SIM card. | | callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1601,7 +2170,7 @@ Unlocks PUK 2 of the SIM card in the specified slot. This API uses a promise to | ------- | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | newPin2 | string | Yes | New PIN 2. | -| puk2 | string | Yes | PUK 2 of the SIM card. | +| puk2 | string | Yes | PUK of the SIM card. | **Return value** @@ -1609,6 +2178,19 @@ Unlocks PUK 2 of the SIM card in the specified slot. This API uses a promise to | ---------------------------------------------------- | -------------------------------------------------- | | Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1646,7 +2228,7 @@ console.log("Result: "+ sim.getMaxSimCount()) getSimIccId(slotId: number, callback: AsyncCallback): void -Obtains the IC card identity (ICCID) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the ICCID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1661,6 +2243,18 @@ Obtains the IC card identity (ICCID) of the SIM card in the specified slot. This | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1694,6 +2288,18 @@ Obtains the ICCID of the SIM card in the specified slot. This API uses a promise | ---------------- | ------------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1724,6 +2330,18 @@ Obtains the voice mailbox alpha identifier of the SIM card in the specified slot | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1757,6 +2375,18 @@ Obtains the voice mailbox alpha identifier of the SIM card in the specified slot | ---------------- | ------------------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1787,6 +2417,18 @@ Obtains the voice mailbox number of the SIM card in the specified slot. This API | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1820,6 +2462,18 @@ Obtains the voice mailbox number of the SIM card in the specified slot. This API | ---------------- | ------------------------------------------------ | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1831,6 +2485,7 @@ promise.then(data => { }); ``` + ## sim.setVoiceMailInfo8+ setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: AsyncCallback): void @@ -1852,6 +2507,19 @@ Sets voice mailbox information for the SIM card in the specified slot. This API | mailNumber | string | Yes | Voice mailbox number. | | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1887,6 +2555,19 @@ Sets voice mailbox information for the SIM card in the specified slot. This API | -------------- | ----------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -1902,7 +2583,7 @@ promise.then(data => { getSimTelephoneNumber(slotId: number, callback: AsyncCallback): void -Obtains the mobile subscriber ISDN number (MSISDN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the MSISDN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1917,6 +2598,18 @@ Obtains the mobile subscriber ISDN number (MSISDN) of the SIM card in the specif | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1950,6 +2643,18 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promis | ---------------- | -------------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1980,6 +2685,18 @@ Obtains the group identifier level 1 (GID1) of the SIM card in the specified slo | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2013,6 +2730,18 @@ Obtains the GID1 of the SIM card in the specified slot. This API uses a promise | ---------------- | ------------------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2043,6 +2772,18 @@ Obtains the international mobile subscriber identity (IMSI) of the SIM card in t | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2076,6 +2817,18 @@ Obtains the IMSI of the SIM card in the specified slot. This API uses a promise | ---------------- | ------------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2106,6 +2859,18 @@ Obtains the carrier configuration of the SIM card in the specified slot. This AP | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2139,6 +2904,18 @@ Obtains the carrier configuration of the SIM card in the specified slot. This AP | --------------------------------------------------- | ----------------------------- | | Promise> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2167,8 +2944,21 @@ Queries contact numbers of the SIM card in the specified slot. This API uses an | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | -| callback | AsyncCallback> | Yes | Callback used to return the result. | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | **Example** @@ -2196,13 +2986,26 @@ Queries contact numbers of the SIM card in the specified slot. This API uses a p | Name| Type | Mandatory| Description | | ------ | ----------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING| **Return value** | Type | Description | | ------------------------------------------------------------ | ------------------------------ | -| Promise> | Promise used to return the result.| +| Promise> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | **Example** @@ -2236,6 +3039,19 @@ Adds contact numbers for the SIM card in the specified slot. This API uses an as | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -2274,7 +3090,20 @@ Adds contact numbers for the SIM card in the specified slot. This API uses a pro | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | **Example** @@ -2312,12 +3141,27 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx" + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2349,7 +3193,20 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | **Example** @@ -2387,12 +3244,27 @@ Updates contact numbers for the SIM card in the specified slot. This API uses an | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx" + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2426,14 +3298,26 @@ Updates contact numbers for the SIM card in the specified slot. This API uses a | -------------- | ----------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js let diallingNumbersInof = { alphaTag: "alpha", number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + recordNumber: 123 }; let promise = sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { @@ -2461,7 +3345,19 @@ Sends an envelope command to the SIM card in the specified slot. This API uses a | -------- | -------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | cmd | string | Yes | Envelope command. | -| callback | AsyncCallback | Yes | Yes | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | **Example** @@ -2497,6 +3393,18 @@ Sends an envelope command to the SIM card in the specified slot. This API uses a | -------------- | --------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2525,9 +3433,21 @@ Sends a terminal response command to the SIM card in the specified slot. This AP | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| cmd | string | Yes | Command | +| cmd | string | Yes | Envelope command. | | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2554,7 +3474,7 @@ Sends a terminal response command to the SIM card in the specified slot. This AP | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| cmd | string | Yes | Command | +| cmd | string | Yes | Envelope command. | **Return value** @@ -2562,6 +3482,18 @@ Sends a terminal response command to the SIM card in the specified slot. This AP | -------------- | --------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -2573,11 +3505,12 @@ promise.then(data => { }); ``` + ## sim.unlockSimLock8+ unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback): void -Unlocks the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2593,6 +3526,19 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba | lockInfo | [PersoLockInfo](#persolockinfo8) | Yes | Personalized lock information. | | callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -2610,7 +3556,7 @@ sim.unlockSimLock(0, persoLockInfo, (err, data) => { unlockSimLock(slotId: number, lockInfo: PersoLockInfo): Promise -Unlocks the SIM card in the specified slot. This API uses a promise to return the result. +Unlocks the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -2631,6 +3577,19 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th | ---------------------------------------------------- | ------------------------- | | Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301002 | SIM card operation error. | + **Example** ```js @@ -2652,8 +3611,6 @@ getOpKey(slotId: number, callback: AsyncCallback): void Obtains the opkey of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2661,14 +3618,34 @@ Obtains the opkey of the SIM card in the specified slot. This API uses an asynch | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 801 | Capability not supported. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | **Example** ```js -sim.getOpKey(0, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); +try { + sim.getOpKey(0, (err, data) => { + if (err) { + console.log("getOpKey failed, err: " + JSON.stringify(err)); + } else { + console.log('getOpKey successfully, data: ' + JSON.stringify(data)); + } + }); +} catch (err) { + console.log("getOpKey err: " + JSON.stringify(err)); +} ``` @@ -2692,15 +3669,27 @@ Obtains the opkey of the SIM card in the specified slot. This API uses a promise | ---------------- | ----------------------------------------- | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 801 | Capability not supported. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js -let promise = sim.getOpKey(0); -promise.then(data => { +try { + let data = sim.getOpKey(0); console.log(`getOpKey success, promise: data->${JSON.stringify(data)}`); -}).catch(err => { - console.log(`getOpKey failed, promise: err->${JSON.stringify(err)}`); -}); +} catch (error) { + console.log(`getOpKey failed, promise: err->${JSON.stringify(error)}`); +} ``` ## sim.getOpName9+ @@ -2718,12 +3707,32 @@ Obtains the OpName of the SIM card in the specified slot. This API uses an async | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 801 | Capability not supported. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js -sim.getOpName(0, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); +try { + sim.getOpName(0, (err, data) => { + if (err) { + console.log("getOpName failed, err: " + JSON.stringify(err)); + } else { + console.log('getOpName successfully, data: ' + JSON.stringify(data)); + } + }); +} catch (err) { + console.log("getOpName err: " + JSON.stringify(err)); +} ``` @@ -2747,15 +3756,27 @@ Obtains the OpName of the SIM card in the specified slot. This API uses a promis | ---------------- | ------------------------------------------ | | Promise | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 801 | Capability not supported. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js -let promise = sim.getOpName(0); -promise.then(data => { +try { + let data = sim.getOpName(0); console.log(`getOpName success, promise: data->${JSON.stringify(data)}`); -}).catch(err => { - console.log(`getOpName failed, promise: err->${JSON.stringify(err)}`); -}); +} catch (error) { + console.log(`getOpName failed, promise: err->${JSON.stringify(error)}`); +} ``` ## SimState @@ -2781,16 +3802,16 @@ Enumerates SIM card types. | Name| Value| Description| | ----- | ----- | ----- | -|UNKNOWN_CARD | -1 | Unknown| -|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| -|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| -|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| -|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| -|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| -|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| -|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| -|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| -|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| +|UNKNOWN_CARD | -1 | Unknown type.| +|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM).| +|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM).| +|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM).| +|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM).| +|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card.| +|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card.| +|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card.| +|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM).| +|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM).| ## LockType8+ @@ -2841,30 +3862,30 @@ Enumerates personalized lock types. ## LockStatusResponse7+ -Defines the lock status response. +Defines the personalized lock information. **System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| result | number | Yes | Operation result. | -| remain?: number | number | Yes | Remaining attempts (can be null).| +| Name | Type | Mandatory| Description | +| --------------- | ------ | ---- | --------------------- | +| result | number | Yes | Operation result. | +| remain?: number | number | No | Remaining attempts (can be null).| ## LockInfo8+ -Defines the lock information. +Defines the personalized lock information. **System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| lockType | [LockType](#locktype8) | Yes | Lock type.| -| password | string | Yes | Password. | -| state | [LockState](#lockstate8) | Yes | Lock state.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | +| lockType | [LockType](#locktype8) | Yes | Lock type.| +| password | string | Yes | Password. | +| state | [LockState](#lockstate8) | Yes | Lock state.| ## PersoLockInfo8+ @@ -2874,10 +3895,10 @@ Defines the personalized lock information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.| -| password | string | Yes | Password. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------- | +| lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.| +| password | string | Yes | Password. | ## IccAccountInfo7+ @@ -2887,15 +3908,15 @@ Defines the ICC account information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| simId | number | Yes | SIM card ID. | -| slotIndex | number | Yes | Card slot ID. | -| isEsim | boolean | Yes | Whether the SIM card is an eSim card.| -| isActive | boolean | Yes | Whether the card is activated. | -| iccId | string | Yes | ICCID number. | -| showName | string | Yes | SIM card display name. | -| showNumber | string | Yes | SIM card display number. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ---------------- | +| simId | number | Yes | SIM card ID. | +| slotIndex | number | Yes | Card slot ID. | +| isEsim | boolean | Yes | Whether the SIM card is an eSim card.| +| isActive | boolean | Yes | Whether the card is activated. | +| iccId | string | Yes | ICCID number. | +| showName | string | Yes | SIM card display name. | +| showNumber | string | Yes | SIM card display number. | ## OperatorConfig8+ @@ -2905,10 +3926,10 @@ Defines the carrier configuration. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| field | string | Yes | Field. | -| value | string | Yes | Value. | +| Name | Type | Mandatory| Description| +| ----- | ------ | ---- | ---- | +| field | string | Yes | Field.| +| value | string | Yes | Value. | ## DiallingNumbersInfo8+ @@ -2918,12 +3939,12 @@ Defines the contact number information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| alphaTag | string | Yes | Alpha tag. | -| number | string | Yes | Contact number. | -| recordNumber | number | Yes | Record number.| -| pin2 | string | Yes | PIN 2.| +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | ---------- | +| alphaTag | string | Yes | Tag. | +| number | string | Yes | Call transfer number. | +| recordNumber | number | Yes | Record number.| +| pin2 | string | Yes | PIN 2.| ## ContactType8+ @@ -2934,7 +3955,7 @@ Enumerates contact types. **System capability**: SystemCapability.Telephony.CoreService | Name | Value | Description | -| -------------- | ---- | ---------- | +| --------------- | ---- | ---------- | | GENERAL_CONTACT | 1 | Common contact number.| | FIXED_DIALING | 2 | Fixed dialing number. | @@ -2946,8 +3967,8 @@ Enumerates carrier configuration keys. **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| ------------------------------------------------------- | ---------------------------------------------------- | -------------------- | +| Name | Value | Description | +| ------------------------------------------------------- | ------------------------------------------------------ | -------------------- | | KEY_VOICE_MAIL_NUMBER_STRING | "voice_mail_number_string" | Voice mailbox number. | | KEY_IMS_SWITCH_ON_BY_DEFAULT_BOOL | "ims_switch_on_by_default_bool" | Fixed dialing number. | | KEY_HIDE_IMS_SWITCH_BOOL | "hide_ims_switch_bool" | Whether to hide the IMS switch. | @@ -2960,7 +3981,7 @@ Enumerates carrier configuration keys. | KEY_IMS_PREFER_FOR_EMERGENCY_BOOL | "ims_prefer_for_emergency_bool" | IMS preferences for emergency. | | KEY_CALL_WAITING_SERVICE_CLASS_INT | "call_waiting_service_class_int" | Call waiting service. | | KEY_CALL_TRANSFER_VISIBILITY_BOOL | "call_transfer_visibility_bool" | Call transfer visibility. | -| KEY_IMS_CALL_DISCONNECT_REASONINFO_MAPPING_STRING_ARRAY | "ims_call_disconnect_reasoninfo_mapping_string_array" | List of IMS call disconnection reasons.| +| KEY_IMS_CALL_DISCONNECT_REASON_INFO_MAPPING_STRING_ARRAY| "ims_call_disconnect_reason_info_mapping_string_array" | List of IMS call disconnection reasons.| | KEY_FORCE_VOLTE_SWITCH_ON_BOOL | "force_volte_switch_on_bool" | Whether to forcibly turn on VoLTE. | | KEY_ENABLE_OPERATOR_NAME_CUST_BOOL | "enable_operator_name_cust_bool" | Whether to display the carrier name.| | KEY_OPERATOR_NAME_CUST_STRING | "operator_name_cust_string" | Carrier name. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 901e3b258b7aa73530935baa81a6366f7aa50e65..c3a1f35f5140514d466ae481876fe1114c2b43e8 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -16,7 +16,7 @@ import sms from '@ohos.telephony.sms'; createMessage\(pdu: Array<number>, specification: string, callback: AsyncCallback\): void -Creates an SMS message instance based on the protocol data unit (PDU) and the specified SMS protocol. This API uses an asynchronous callback to return the result. +Creates an SMS instance based on the protocol data unit (PDU) and specified SMS protocol. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.SmsMms @@ -44,7 +44,7 @@ sms.createMessage(pdu, specification, (err, data) => { createMessage\(pdu: Array<number>, specification: string\): Promise -Creates an SMS message instance based on the PDU and the specified SMS protocol. This API uses a promise to return the result. +Creates an SMS instance based on the PDU and specified SMS protocol. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.SmsMms @@ -81,7 +81,7 @@ sendMessage(options: SendMessageOptions): void Sends an SMS message. -**Required permission**: ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -114,7 +114,7 @@ sms.sendMessage(options); getDefaultSmsSlotId\(callback: AsyncCallback<number>\): void -Obtains the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. +Obtains the default slot ID of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.SmsMms @@ -122,7 +122,7 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the result.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<number> | Yes | Callback used to return the result.
- **0**: card slot 1
- **1**: card slot 2| **Example** @@ -137,7 +137,7 @@ sms.getDefaultSmsSlotId((err, data) => { getDefaultSmsSlotId\(\): Promise<number> -Obtains the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. +Obtains the default slot ID of the SIM card used to send SMS messages. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.SmsMms @@ -162,11 +162,11 @@ promise.then(data => { setDefaultSmsSlotId\(slotId: number, callback: AsyncCallback<void>\): void -Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. +Sets the default slot ID of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.SET_TELEPHONY_STATE +**Required permissions**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.SmsMms @@ -174,9 +174,21 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -190,11 +202,11 @@ sms.setDefaultSmsSlotId(0, (err, data) => { setDefaultSmsSlotId\(slotId: number\): Promise<void> -Sets the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. +Sets the default slot ID of the SIM card used to send SMS messages. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.SET_TELEPHONY_STATE +**Required permissions**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.SmsMms @@ -202,13 +214,25 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | **Example** @@ -229,7 +253,7 @@ Sets the short message service center (SMSC) address. This API uses an asynchron **System API**: This is a system API. -**Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) +**Required permissions**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms @@ -241,6 +265,17 @@ Sets the short message service center (SMSC) address. This API uses an asynchron | smscAddr | string | Yes | SMSC address. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -260,7 +295,7 @@ Sets the SMSC address. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) +**Required permissions**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms @@ -277,6 +312,17 @@ Sets the SMSC address. This API uses a promise to return the result. | ------------------- | ------------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -299,7 +345,7 @@ Obtains the SMSC address. This API uses an asynchronous callback to return the r **System API**: This is a system API. -**Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) +**Required permissions**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms @@ -310,6 +356,17 @@ Obtains the SMSC address. This API uses an asynchronous callback to return the r | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<string> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -328,7 +385,7 @@ Obtains the SMSC address. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) +**Required permissions**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms @@ -344,6 +401,17 @@ Obtains the SMSC address. This API uses a promise to return the result. | --------------------- | --------------------------------------------- | | Promise<string> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -360,7 +428,7 @@ promise.then(data => { hasSmsCapability(): boolean -Checks whether the current device can send and receive SMS messages. This API returns the result synchronously. +Checks whether the current device can send and receive SMS messages. This API works in synchronous mode. **System capability**: SystemCapability.Telephony.SmsMms @@ -383,7 +451,7 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call **System API**: This is a system API. -**Required permission**: ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -394,6 +462,17 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call | content | string | Yes | SMS message content. The value cannot be null.| | callback | AsyncCallback> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -412,7 +491,7 @@ Splits an SMS message into multiple segments. This API uses a promise to return **System API**: This is a system API. -**Required permission**: ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -428,6 +507,17 @@ Splits an SMS message into multiple segments. This API uses a promise to return | ----------------------- | ----------------------------------- | | Promise> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -448,7 +538,7 @@ Adds a SIM message. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -459,6 +549,17 @@ Adds a SIM message. This API uses an asynchronous callback to return the result. | options | [SimMessageOptions](#simmessageoptions7) | Yes | SIM message options.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -482,7 +583,7 @@ Adds a SIM message. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -498,6 +599,17 @@ Adds a SIM message. This API uses a promise to return the result. | ------------------- | ----------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -523,7 +635,7 @@ Deletes a SIM message. This API uses an asynchronous callback to return the resu **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -535,6 +647,17 @@ Deletes a SIM message. This API uses an asynchronous callback to return the resu | msgIndex | number | Yes | Message index. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -554,7 +677,7 @@ Deletes a SIM message. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -571,6 +694,17 @@ Deletes a SIM message. This API uses a promise to return the result. | ------------------- | ----------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -592,7 +726,7 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -603,6 +737,17 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu | options | [UpdateSimMessageOptions](#updatesimmessageoptions7) | Yes | SIM message updating options.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -627,7 +772,7 @@ Updates a SIM message. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES +**Required permissions**: ohos.permission.RECEIVE_SMS and ohos.permission.SEND_MESSAGES **System capability**: SystemCapability.Telephony.SmsMms @@ -643,6 +788,17 @@ Updates a SIM message. This API uses a promise to return the result. | ------------------- | ----------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -669,7 +825,7 @@ Obtains all SIM card messages. This API uses an asynchronous callback to return **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS +**Required permissions**: ohos.permission.RECEIVE_SMS **System capability**: SystemCapability.Telephony.SmsMms @@ -680,6 +836,17 @@ Obtains all SIM card messages. This API uses an asynchronous callback to return | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -698,7 +865,7 @@ Obtains all SIM card messages. This API uses a promise to return the result. **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS +**Required permissions**: ohos.permission.RECEIVE_SMS **System capability**: SystemCapability.Telephony.SmsMms @@ -714,6 +881,17 @@ Obtains all SIM card messages. This API uses a promise to return the result. | ------------------------------------------------------- | ---------------------------------- | | PromiseArray<[SimShortMessage](#simshortmessage7)\>> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -734,7 +912,7 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS +**Required permissions**: ohos.permission.RECEIVE_SMS **System capability**: SystemCapability.Telephony.SmsMms @@ -745,6 +923,17 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to | options | [CBConfigOptions](#cbconfigoptions7) | Yes | Cell broadcast configuration options.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -769,7 +958,7 @@ Sets the cell broadcast configuration. This API uses a promise to return the res **System API**: This is a system API. -**Required permission**: ohos.permission.RECEIVE_SMS +**Required permissions**: ohos.permission.RECEIVE_SMS **System capability**: SystemCapability.Telephony.SmsMms @@ -785,6 +974,17 @@ Sets the cell broadcast configuration. This API uses a promise to return the res | ------------------- | ----------------------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -820,7 +1020,17 @@ Obtains SMS message segment information. This API uses an asynchronous callback | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | message | string | Yes | SMS message. | | force7bit | boolean | Yes | Whether to use 7-bit coding. | -| callback | | Yes | Callback used to return the result. | +| callback | AsyncCallback<[SmsSegmentsInfo](#smssegmentsinfo8)> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -847,14 +1057,24 @@ Obtains SMS message segment information. This API uses a promise to return the r | Name | Type | Mandatory| Description | | --------- | ------- | ---- | ----------------------------------------- | | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| message | string | Yes | Message | +| message | string | Yes | SMS message. | | force7bit | boolean | Yes | Whether to use 7-bit coding. | **Return value** | Type | Description | | ------------------------------------------------------- | ----------------------------- | -| | Promise used to return the result.| +| Promise<[SmsSegmentsInfo](#smssegmentsinfo8)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | **Example** @@ -885,6 +1105,16 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -899,7 +1129,7 @@ sms.isImsSmsSupported(slotId, (err, data) => { isImsSmsSupported(slotId: number): Promise -Checks whether SMS is supported on IMS. This API uses a promise to return the result. +This API uses an asynchronous callback to return the result. This API uses a promise to return the result. **System API**: This is a system API. @@ -917,6 +1147,16 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re | ---------------------- | ----------------------- | | Promise<boolean> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -945,6 +1185,17 @@ Obtains the SMS format supported by the IMS. This API uses an asynchronous callb | -------- | --------------------------- | ---- | ---------- | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -970,6 +1221,17 @@ Obtains the SMS format supported by the IMS. This API uses a promise to return t | --------------------- | -------------------------- | | Promise<string> | Promise used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -998,6 +1260,16 @@ Decodes MMS messages. This API uses an asynchronous callback to return the resul | mmsFilePathName | string \|Array | Yes | MMS message file path.| | callback | AsyncCallback<[MmsInformation](#mmsinformation8)> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1030,6 +1302,16 @@ Decodes MMS messages. This API uses a promise to return the result. | --------------------------------------------------------- | --------------------------- | | Promise<<[MmsInformation](#mmsinformation8)>> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1046,7 +1328,7 @@ promise.then(data => { encodeMms(mms: MmsInformation, callback: AsyncCallback>): void -Encodes MMS messages. This API uses an asynchronous callback to return the result. +MMS message code. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1059,6 +1341,16 @@ Encodes MMS messages. This API uses an asynchronous callback to return the resul | mms | [MmsInformation](#mmsinformation8) | Yes | MMS message information.| | callback | AsyncCallback<Array> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1081,7 +1373,7 @@ sms.encodeMms(mmsInformation, (err, data) => { encodeMms(mms: MmsInformation): Promise> -Encodes MMS messages. This API uses a promise to return the result. +MMS message code. This API uses a promise to return the result. **System API**: This is a system API. @@ -1099,6 +1391,16 @@ Encodes MMS messages. This API uses a promise to return the result. | ----------------------------- | ----------------------------------- | | Promise<Array> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -1125,19 +1427,19 @@ Defines an SMS message instance. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| hasReplyPath | boolean | Yes |Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| -| isReplaceMessage | boolean | Yes |Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| -| isSmsStatusReportMessage | boolean | Yes |Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| -| messageClass | [ShortMessageClass](#shortmessageclass) | Yes | SMS message type. | -| pdu | Array<number> | Yes | PDU in the SMS message. | -| protocolId | number | Yes | Protocol identifier used for delivering the SMS message. | -| scAddress | string | Yes | SMSC address. | -| scTimestamp | number | Yes | SMSC timestamp. | -| status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| -| visibleMessageBody | string | Yes | SMS message body. | -| visibleRawAddress | string | Yes | Sender address. | +| Name | Type | Mandatory| Description | +| ------------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | +| hasReplyPath | boolean | Yes | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
TP-Reply-Path: The device returns a response based on the SMSC that sends the SMS message. | +| isReplaceMessage | boolean | Yes | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| +| isSmsStatusReportMessage | boolean | Yes | Whether the received SMS message is an SMS delivery report. The default value is **false**.
SMS delivery report: a message sent from the SMSC to show the current status of the SMS message you delivered.| +| messageClass | [ShortMessageClass](#shortmessageclass) | Yes | Enumerates SMS message types. | +| pdu | Array<number> | Yes | PDU in the SMS message. | +| protocolId | number | Yes | Protocol identifier used for delivering the SMS message. | +| scAddress | string | Yes | SMSC address. | +| scTimestamp | number | Yes | SMSC timestamp. | +| status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| +| visibleMessageBody | string | Yes | SMS message body. | +| visibleRawAddress | string | Yes | Sender address. | ## ShortMessageClass @@ -1161,7 +1463,7 @@ Provides the options (including callbacks) for sending an SMS message. For examp **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Slot ID of the SIM card used for sending SMS messages.
- **0**: card slot 1
- **1**: card slot 2 | | destinationHost | string | Yes | Destination address of the SMS message. | @@ -1178,22 +1480,22 @@ Provides the callback for the SMS message sending result. It consists of three p **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ----------------------------------------------------------------------------------------- | | isLastPart | boolean | No | Whether this SMS message is the last part of a long SMS message. The value **true** indicates that this SMS message is the last part of a long SMS message, and value **false** indicates the opposite. The default value is **false**.| -| result | [SendSmsResult](#sendsmsresult) | Yes | SMS message sending result. | -| url | string | Yes | URI for storing the sent SMS message. | +| result | [SendSmsResult](#sendsmsresult) | Yes | SMS message sending result. | +| url | string | Yes | URI for storing the sent SMS message. | ## IDeliveryShortMessageCallback -Provides the callback for the SMS message delivery report. +Provides the callback for the SMS message delivery report. **System capability**: SystemCapability.Telephony.SmsMms | Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | -------------- | -| pdu | Array<number> | Yes | SMS message delivery report.| +| ---- | ------------------- | ---- | -------------- | +| pdu | Array<number> | Yes | SMS message delivery report.| ## SendSmsResult @@ -1209,7 +1511,6 @@ Enumerates SMS message sending results. | SEND_SMS_FAILURE_RADIO_OFF | 2 | Failed to send the SMS message because the modem is shut down. | | SEND_SMS_FAILURE_SERVICE_UNAVAILABLE | 3 | Failed to send the SMS message because the network is unavailable or SMS message sending or receiving is not supported.| - ## MmsInformation8+ Defines the MMS message information. @@ -1218,10 +1519,10 @@ Defines the MMS message information. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------------------------------------ | ---- | --------- | -| messageType | [MessageType](#messagetype8) | Yes | Message type. | -| mmsType | [MmsSendReq](#mmssendreq8) \|[MmsSendConf](#mmssendconf8) \|[MmsNotificationInd](#mmsnotificationind8) \|[MmsRespInd](#mmsrespind8) \|[MmsRetrieveConf](#mmsretrieveconf8)\|[MmsAcknowledgeInd](#mmsacknowledgeind8)\|[MmsDeliveryInd](#mmsdeliveryind8)\|[MmsReadOrigInd](#mmsreadorigind8)\|[MmsReadRecInd](#mmsreadrecind8)| Yes | PDU header type.| +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ---------- | +| messageType | [MessageType](#messagetype8) | Yes | Message type.| +| mmsType | [MmsSendReq](#mmssendreq8) \|[MmsSendConf](#mmssendconf8) \|[MmsNotificationInd](#mmsnotificationind8) \|[MmsRespInd](#mmsrespind8) \|[MmsRetrieveConf](#mmsretrieveconf8)\|[MmsAcknowledgeInd](#mmsacknowledgeind8)\|[MmsDeliveryInd](#mmsdeliveryind8)\|[MmsReadOrigInd](#mmsreadorigind8)\|[MmsReadRecInd](#mmsreadrecind8) | Yes | PDU header type.| | attachment | Array<[MmsAttachment](#mmsattachment8)\> | No | Attachment. | ## MmsSendReq8+ @@ -1232,13 +1533,13 @@ Defines an MMS message sending request. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------------- | ------------------------------------ | ---- | ------------ | | from | [MmsAddress](#mmsaddress8) | Yes | MMS message source. | | transactionId | string | Yes | Transaction ID. | | contentType | string | Yes | Content type. | | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | -| to | Array<[MmsAddress](#mmsaddress8)\> | No | Address to which the message is sent. | +| to | Array<[MmsAddress](#mmsaddress8)\> | No | Destination address. | | date | number | No | Date. | | cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | | bcc | Array<[MmsAddress](#mmsaddress8)\> | No | Blind carbon copy. | @@ -1258,7 +1559,7 @@ Defines the MMS message sending configuration. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------- | ---- | -------- | | responseState | number | Yes | Response status.| | transactionId | string | Yes | Transaction ID. | @@ -1273,7 +1574,7 @@ Defines an MMS notification index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | --------------- | ---------------------------------- | ---- | -------- | | transactionId | string | Yes | Transaction ID. | | messageClass | number | Yes | Message class. | @@ -1281,7 +1582,7 @@ Defines an MMS notification index. | expiry | number | Yes | Expiration. | | contentLocation | string | Yes | Content location.| | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | -| from | [MmsAddress](#mmsaddress8) | No | Source. | +| from | [MmsAddress](#mmsaddress8) | No | Source address. | | subject | string | No | Subject. | | deliveryReport | number | No | Status report.| | contentClass | number | No | Content class. | @@ -1294,7 +1595,7 @@ Defines an MMS confirmation index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------- | ---- | -------- | | transactionId | string | Yes | Transaction ID. | | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | @@ -1308,15 +1609,15 @@ Defines the MMS message retrieval configuration. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------------- | ------------------------------------ | ---- | -------- | | transactionId | string | Yes | Transaction ID. | | messageId | string | Yes | Message ID. | | date | number | Yes | Date. | | contentType | string | Yes | Content type.| -| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | -| version | [MmsVersionType](#mmsversiontype8) | Yes | Version | -| from | [MmsAddress](#mmsaddress8) | No | Source. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Destination address. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| from | [MmsAddress](#mmsaddress8) | No | Source address. | | cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | | subject | string | No | Subject. | | priority | [MmsPriorityType](#mmsprioritytype8) | No | Priority. | @@ -1333,16 +1634,15 @@ Defines the original MMS message reading index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ---------------------------------- | ---- | -------- | | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | | messageId | string | Yes | Message ID. | -| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | -| from | [MmsAddress](#mmsaddress8) | Yes | Source. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Destination address. | +| from | [MmsAddress](#mmsaddress8) | Yes | Source address. | | date | number | Yes | Date. | | readStatus | number | Yes | Read status.| - ## MmsReadRecInd8+ Defines the MMS message reading index. @@ -1351,16 +1651,15 @@ Defines the MMS message reading index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ---------------------------------- | ---- | -------- | -| version | [MmsVersionType](#mmsversiontype8) | Yes | Version | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | | messageId | string | Yes | Message ID. | -| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Destination. | -| from | [MmsAddress](#mmsaddress8) | Yes | Source. | -| readStatus | number | Yes | Read state.| +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Destination address. | +| from | [MmsAddress](#mmsaddress8) | Yes | Source address. | +| readStatus | number | Yes | Read status.| | date | number | No | Date. | - ## MmsAttachment8+ Defines the attachment of an MMS message. @@ -1369,7 +1668,7 @@ Defines the attachment of an MMS message. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ----------------------- | ------------------------------------ | ---- | ------------------ | | contentId | string | Yes | Content ID. | | contentLocation | string | Yes | Content location. | @@ -1378,7 +1677,7 @@ Defines the attachment of an MMS message. | contentType | string | Yes | Content type. | | isSmil | boolean | Yes | Whether the synchronized multimedia integration language is used.| | path | string | No | Path. | -| inBuff | Array | No | In the buffer | +| inBuff | Array | No | Whether the message is in the buffer. | | fileName | string | No | File name. | | charset | [MmsCharSets](#mmscharsets8) | No | Character set. | @@ -1390,20 +1689,20 @@ Defines an MMSC address. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ---------------------------- | ---- | ------ | -| address | string | Yes | MMSC address. | +| address | string | Yes | Network address. | | charset | [MmsCharSets](#mmscharsets8) | Yes | Character set.| ## MessageType8+ -Enumerates message types. +Message type. **System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | ------------------------- | ---- | -------------------- | | TYPE_MMS_SEND_REQ | 128 | MMS message sending request. | | TYPE_MMS_SEND_CONF | 129 | MMS message sending configuration. | @@ -1423,7 +1722,7 @@ Enumerates MMS message priorities. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | ---------- | ---- | -------------- | | MMS_LOW | 128 | Low priority. | | MMS_NORMAL | 129 | Normal priority.| @@ -1437,7 +1736,7 @@ Enumerates MMS versions. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | --------------- | ---- | ----------- | | MMS_VERSION_1_0 | 0x10 | MMS version 1_0.| | MMS_VERSION_1_1 | 0x11 | MMS version 1_1.| @@ -1452,7 +1751,7 @@ Enumerates MMS character sets. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | --------------- | ------ | ------------------- | | BIG5 | 0X07EA | BIG5 format. | | ISO_10646_UCS_2 | 0X03E8 | ISO_10646_UCS_2 format.| @@ -1477,7 +1776,7 @@ Enumerates disposition types. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | ---------- | ---- | -------- | | FROM_DATA | 0 | Data source.| | ATTACHMENT | 1 | Attachment. | @@ -1491,7 +1790,7 @@ Enumerates report types. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description| +| Name | Value | Description| | ------- | ---- | ---- | | MMS_YES | 128 | YES | | MMS_NO | 129 | NO | @@ -1504,7 +1803,7 @@ Defines the cell broadcast configuration options. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------------- | -------------------- | ---- | ------------ | | slotId | number | Yes | Card slot ID. | | enable | boolean | Yes | Whether to enable cell broadcast. | @@ -1520,7 +1819,7 @@ Defines the SIM message status. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | ------------------------- | ---- | --------------------------- | | SIM_MESSAGE_STATUS_FREE | 0 | Free state. | | SIM_MESSAGE_STATUS_READ | 1 | Read state. | @@ -1530,13 +1829,13 @@ Defines the SIM message status. ## RanType7+ -Enumerates RAN types. +RAN type. **System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description| +| Name | Value | Description| | --------- | ---- | ---- | | TYPE_GSM | 1 | GSM | | TYPE_CDMA | 2 | CMDA | @@ -1549,7 +1848,7 @@ Enumerates SMS encoding schemes. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Value | Description | +| Name | Value | Description | | -------------------- | ---- | ------------ | | SMS_ENCODING_UNKNOWN | 0 | Unknown code.| | SMS_ENCODING_7BIT | 1 | 7-digit code. | @@ -1564,12 +1863,12 @@ Defines the SIM message options. **System capability**: SystemCapability.Telephony.SmsMms -| Name| Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | -------------- | | slotId | number | Yes | Card slot ID. | | smsc | string | Yes | Short message service center.| | pdu | string | Yes | Protocol data unit. | -| status | [SimMessageStatus](#simmessagestatus7) | Yes | Message status. | +| status | [SimMessageStatus](#simmessagestatus7) | Yes | Status. | ## UpdateSimMessageOptions7+ @@ -1579,7 +1878,7 @@ Defines the updating SIM message options. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | --------- | -------------------------------------- | ---- | -------------- | | slotId | number | Yes | Card slot ID. | | msgIndex | number | Yes | Message index. | @@ -1595,7 +1894,7 @@ Defines a SIM message. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------------- | -------------------------------------- | ---- | ------------- | | shortMessage | [ShortMessage](#shortmessage) | Yes | SMS message. | | simMessageStatus | [SimMessageStatus](#simmessagestatus7) | Yes | SIM message status.| @@ -1609,12 +1908,12 @@ Defines an MMS message delivery index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | --------- | ---------------------------------- | ---- | ------ | | messageId | string | Yes | Message ID.| | date | number | Yes | Date. | -| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent.| -| status | number | Yes | Status. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Destination address.| +| status | number | Yes | Status | | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | ## MmsRespInd8+ @@ -1625,10 +1924,10 @@ Defines an MMS response index. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------- | ---- | -------- | | transactionId | string | Yes | Event ID. | -| status | number | Yes | Status. | +| status | number | Yes | Status | | version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | | reportAllowed | [ReportType](#reporttype8) | No | Report allowed.| @@ -1640,7 +1939,7 @@ Defines the SMS message segment information. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------------------- | ---------------------------------------- | ---- | ------------ | | splitCount | number | Yes | Split count. | | encodeCount | number | Yes | Encoding count. | diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index bd14137464ce195f5c61b9d6a53ce6ef79cd3f10..626107db787301b55615b8354996e149eff20ede 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,8 +1,9 @@ -# @ohos.net.socket (Socket Connection) +# # @ohos.net.socket (Socket Connection) -The **socket** module implements socket connection management and operation. +The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,7 +14,7 @@ import socket from '@ohos.net.socket'; ## socket.constructUDPSocketInstance -constructUDPSocketInstance\(\): UDPSocket +constructUDPSocketInstance(): UDPSocket Creates a **UDPSocket** object. @@ -22,7 +23,7 @@ Creates a **UDPSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| @@ -39,7 +40,7 @@ Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. @@ -54,6 +55,13 @@ Binds the IP address and port number. The port number can be specified or random | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -70,7 +78,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. @@ -84,11 +92,17 @@ Binds the IP address and port number. The port number can be specified or random | ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -106,7 +120,7 @@ promise .then(() => { ### send -send\(options: UDPSendOptions, callback: AsyncCallback\): void +send(options: UDPSendOptions, callback: AsyncCallback\): void Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -123,6 +137,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -146,7 +167,7 @@ udp.send({ ### send -send\(options: UDPSendOptions\): Promise +send(options: UDPSendOptions): Promise\ Sends data over a UDPSocket connection. This API uses a promise to return the result. @@ -162,10 +183,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Return value** | Type | Description | -| -------------- | --------------------------------------------- | +| :-------------- | :--------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -190,7 +218,7 @@ promise.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -220,7 +248,7 @@ udp.close(err => { ### close -close\(\): Promise +close(): Promise\ Closes a UDPSocket connection. This API uses a promise to return the result. @@ -231,7 +259,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -249,12 +277,12 @@ promise.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -266,6 +294,12 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca | -------- | ------------------------------------------------------ | ---- | ---------- | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -289,12 +323,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### getState -getState\(\): Promise +getState(): Promise\ Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -303,8 +337,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | -| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| +| :----------------------------------------------- | :----------------------------------------- | +| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| **Example** @@ -328,12 +362,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): void -Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. +Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -346,6 +380,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -376,12 +416,12 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions\): Promise +setExtraOptions(options: UDPExtraOptions): Promise\ -Sets other properties of the UDPSocket connection. This API uses a promise to return the result. +Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -396,9 +436,16 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -424,9 +471,9 @@ promise.then(() => { ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -437,7 +484,7 @@ Enables listening for message receiving events of the UDPSocket connection. This | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | type | string | Yes | Type of the event to subscribe to.
**message**: message receiving event| -| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | +| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. | **Example** @@ -449,13 +496,13 @@ udp.on('message', value => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -475,15 +522,15 @@ let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } udp.on('message', callback); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. udp.off('message', callback); udp.off('message'); ``` -### on\('listening' | 'close'\) +### on('listening' | 'close') -on\(type: 'listening' | 'close', callback: Callback\): void +on(type: 'listening' | 'close', callback: Callback\): void Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -509,13 +556,13 @@ udp.on('close', () => { ``` -### off\('listening' | 'close'\) +### off('listening' | 'close') -off\(type: 'listening' | 'close', callback?: Callback\): void +off(type: 'listening' | 'close', callback?: Callback\): void Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -535,22 +582,22 @@ let callback1 = () =>{ console.log("on listening, success"); } udp.on('listening', callback1); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. udp.off('listening', callback1); udp.off('listening'); let callback2 = () =>{ console.log("on close, success"); } udp.on('close', callback2); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. udp.off('close', callback2); udp.off('close'); ``` -### on\('error'\) +### on('error') -on\(type: 'error', callback: ErrorCallback\): void +on(type: 'error', callback: ErrorCallback): void Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -563,7 +610,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an | type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -574,13 +620,13 @@ udp.on('error', err => { ``` -### off\('error'\) +### off('error') -off\(type: 'error', callback?: ErrorCallback\): void +off(type: 'error', callback?: ErrorCallback): void Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -600,7 +646,7 @@ let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } udp.on('error', callback); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. udp.off('error', callback); udp.off('error'); ``` @@ -668,9 +714,15 @@ Defines information about the socket connection. | port | number | Yes | Port number. The value ranges from **0** to **65535**. | | size | number | Yes | Length of the server response message, in bytes. | +## Description of UDP Error Codes + +The UDP error code mapping is in the format of 2301000 + Linux kernel error code. + +For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). + ## socket.constructTCPSocketInstance -constructTCPSocketInstance\(\): TCPSocket +constructTCPSocketInstance(): TCPSocket Creates a **TCPSocket** object. @@ -679,7 +731,7 @@ Creates a **TCPSocket** object. **Return value** | Type | Description | - | --------------------------------- | ---------------------- | + | :--------------------------------- | :---------------------- | | [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** @@ -695,7 +747,7 @@ Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. @@ -710,6 +762,12 @@ Binds the IP address and port number. The port number can be specified or random | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -727,7 +785,7 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. @@ -744,9 +802,16 @@ Binds the IP address and port number. The port number can be specified or random **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -762,10 +827,13 @@ promise.then(() => { ### connect -connect\(options: TCPConnectOptions, callback: AsyncCallback\): void +connect(options: TCPConnectOptions, callback: AsyncCallback\): void Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. +>**NOTE** +>This API can be called only after **bind** is successfully called. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -777,6 +845,13 @@ Sets up a connection to the specified IP address and port number. This API uses | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -793,7 +868,7 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time ### connect -connect\(options: TCPConnectOptions\): Promise +connect(options: TCPConnectOptions): Promise\ Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. @@ -810,9 +885,16 @@ Sets up a connection to the specified IP address and port number. This API uses **Return value** | Type | Description | -| -------------- | --------------------------------------------------------- | +| :-------------- | :--------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -828,12 +910,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions, callback: AsyncCallback\): void +send(options: TCPSendOptions, callback: AsyncCallback\): void Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -846,6 +928,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -870,12 +959,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions\): Promise +send(options: TCPSendOptions): Promise\ Sends data over a TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -890,9 +979,16 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re **Return value** | Type | Description | -| -------------- | ------------------------------------------------- | +| :-------------- | :------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -916,7 +1012,7 @@ promise1.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. @@ -930,6 +1026,11 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return | -------- | --------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -947,7 +1048,7 @@ tcp.close(err => { ### close -close\(\): Promise +close(): Promise\ Closes a TCPSocket connection. This API uses a promise to return the result. @@ -958,9 +1059,15 @@ Closes a TCPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -976,12 +1083,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -993,6 +1100,12 @@ Obtains the remote address of a socket connection. This API uses an asynchronous | -------- | ------------------------------------------------- | ---- | ---------- | | callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1015,12 +1128,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(\): Promise +getRemoteAddress(): Promise\ Obtains the remote address of a socket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1029,9 +1142,15 @@ Obtains the remote address of a socket connection. This API uses a promise to re **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise<[NetAddress](#netaddress)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1053,12 +1172,12 @@ promise1.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1070,6 +1189,11 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca | -------- | ------------------------------------------------------ | ---- | ---------- | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1093,12 +1217,12 @@ promise.then(() => { ### getState -getState\(\): Promise +getState(): Promise\ Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1107,9 +1231,14 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1132,12 +1261,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1150,6 +1279,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -1181,12 +1317,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1201,9 +1337,15 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -1233,9 +1375,9 @@ promise.then(() => { ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. @@ -1258,13 +1400,13 @@ tcp.on('message', value => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1284,15 +1426,15 @@ let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } tcp.on('message', callback); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. tcp.off('message', callback); tcp.off('message'); ``` -### on\('connect' | 'close'\) +### on('connect' | 'close') -on\(type: 'connect' | 'close', callback: Callback\): void +on(type: 'connect' | 'close', callback: Callback\): void Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. @@ -1305,7 +1447,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th | type | string | Yes | Type of the event to subscribe to.

- **connect**: connection event
- **close**: close event| | callback | Callback\ | Yes | Callback used to return the result. | - **Example** ```js @@ -1319,13 +1460,13 @@ tcp.on('close', data => { ``` -### off\('connect' | 'close'\) +### off('connect' | 'close') -off\(type: 'connect' | 'close', callback?: Callback\): void +off(type: 'connect' | 'close', callback?: Callback\): void Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1345,22 +1486,22 @@ let callback1 = () =>{ console.log("on connect success"); } tcp.on('connect', callback1); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. tcp.off('connect', callback1); tcp.off('connect'); let callback2 = () =>{ console.log("on close success"); } tcp.on('close', callback2); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. tcp.off('close', callback2); tcp.off('close'); ``` -### on\('error'\) +### on('error') -on\(type: 'error', callback: ErrorCallback\): void +on(type: 'error', callback: ErrorCallback): void Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. @@ -1383,13 +1524,13 @@ tcp.on('error', err => { ``` -### off\('error'\) +### off('error') -off\(type: 'error', callback?: ErrorCallback\): void +off(type: 'error', callback?: ErrorCallback): void Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1409,7 +1550,7 @@ let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } tcp.on('error', callback); -// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. +// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. tcp.off('error', callback); tcp.off('error'); ``` @@ -1452,7 +1593,13 @@ Defines other properties of the TCPSocket connection. | receiveBufferSize | number | No | Size of the receive buffer, in bytes. | | sendBufferSize | number | No | Size of the send buffer, in bytes. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | -| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | +| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. | + +## Description of TCP Error Codes + +The TCP error code mapping is in the format of 2301000 + Linux kernel error code. + +For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). ## socket.constructTLSSocketInstance9+ @@ -1465,7 +1612,7 @@ Creates a **TLSSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [TLSSocket](#tlssocket9) | **TLSSocket** object.| **Example** @@ -1480,7 +1627,7 @@ Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call ### bind9+ -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. This API uses an asynchronous callback to return the result. @@ -1518,7 +1665,7 @@ tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind9+ -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ Binds the IP address and port number. This API uses a promise to return the result. @@ -1535,7 +1682,7 @@ Binds the IP address and port number. This API uses a promise to return the resu **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1560,7 +1707,7 @@ promise.then(() => { ### getState9+ -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result. @@ -1600,7 +1747,7 @@ tls.getState((err, data) => { ### getState9+ -getState\(\): Promise +getState(): Promise\ Obtains the status of the TLSSocket connection. This API uses a promise to return the result. @@ -1609,7 +1756,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1639,7 +1786,7 @@ promise.then(() => { ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result. @@ -1691,7 +1838,7 @@ tls.setExtraOptions({ ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result. @@ -1706,7 +1853,7 @@ Sets other properties of the TCPSocket connection after successful binding of th **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1746,7 +1893,7 @@ promise.then(() => { ### connect9+ -connect(options: TLSConnectOptions, callback: AsyncCallback\): void +connect(options: TLSConnectOptions, callback: AsyncCallback\): void Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result. @@ -1767,7 +1914,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1784,7 +1930,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication -tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1795,14 +1941,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "192.168.xx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1810,12 +1956,12 @@ let options = { }, }; tlsTwoWay.connect(options, (err, data) => { - console.error(err); - console.log(data); + console.error("connect callback error"+err); + console.log(JSON.stringify(data)); }); let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication -tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1825,7 +1971,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1834,14 +1980,14 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error(err); - console.log(data); + console.error("connect callback error"+err); + console.log(JSON.stringify(data)); }); ``` ### connect9+ -connect(options: TLSConnectOptions): Promise\ +connect(options: TLSConnectOptions): Promise\ Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result. @@ -1857,7 +2003,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.| **Error codes** @@ -1867,7 +2013,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1884,7 +2029,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication -tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1895,14 +2040,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "xxxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1910,13 +2055,13 @@ let options = { }, }; tlsTwoWay.connect(options).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication -tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1926,7 +2071,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1935,7 +2080,7 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -1943,7 +2088,7 @@ tlsOneWay.connect(oneWayOptions).then(data => { ### getRemoteAddress9+ -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result. @@ -1953,7 +2098,7 @@ Obtains the remote address of a TLSSocket connection. This API uses an asynchron | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.| +| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.| **Error codes** @@ -1976,7 +2121,7 @@ tls.getRemoteAddress((err, data) => { ### getRemoteAddress9+ -getRemoteAddress\(\): Promise\ +getRemoteAddress(): Promise\ Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result. @@ -1985,7 +2130,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2008,7 +2153,7 @@ promise.then(() => { ### getCertificate9+ -getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void +getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. @@ -2018,7 +2163,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe | Name | Type | Mandatory| Description| | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.| +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.| **Error codes** @@ -2042,7 +2187,7 @@ tls.getCertificate((err, data) => { ### getCertificate9+ -getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> +getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. @@ -2050,9 +2195,9 @@ Obtains the local digital certificate after a TLSSocket connection is establishe **Return value** -| Type | Description | +| Type | Description | | -------------- | -------------------- | -| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2074,7 +2219,7 @@ tls.getCertificate().then(data => { ### getRemoteCertificate9+ -getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void +getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. @@ -2084,7 +2229,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es | Name | Type | Mandatory | Description | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2107,7 +2252,7 @@ tls.getRemoteCertificate((err, data) => { ### getRemoteCertificate9+ -getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> +getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result. @@ -2117,7 +2262,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es | Type | Description | | -------------- | -------------------- | -| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2138,7 +2283,7 @@ tls.getRemoteCertificate().then(data => { ### getProtocol9+ -getProtocol(callback: AsyncCallback\): void +getProtocol(callback: AsyncCallback\): void Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. @@ -2148,7 +2293,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab | Name | Type | Mandatory| Description | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2172,7 +2317,7 @@ tls.getProtocol((err, data) => { ### getProtocol9+ -getProtocol():Promise\ +getProtocol():Promise\ Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result. @@ -2182,7 +2327,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab | Type | Description | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2204,7 +2349,7 @@ tls.getProtocol().then(data => { ### getCipherSuite9+ -getCipherSuite(callback: AsyncCallback\>): void +getCipherSuite(callback: AsyncCallback\\>): void Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. @@ -2214,7 +2359,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc | Name | Type | Mandatory| Description| | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2239,7 +2384,7 @@ tls.getCipherSuite((err, data) => { ### getCipherSuite9+ -getCipherSuite(): Promise\> +getCipherSuite(): Promise\\> Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result. @@ -2249,7 +2394,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc | Type | Description | | ---------------------- | --------------------- | -| Promise\> | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\\> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2264,7 +2409,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ```js tls.getCipherSuite().then(data => { - console.log(data); + console.log('getCipherSuite success:' + JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -2272,7 +2417,7 @@ tls.getCipherSuite().then(data => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(callback: AsyncCallback\>): void +getSignatureAlgorithms(callback: AsyncCallback\\>): void Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. @@ -2282,7 +2427,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T | Name | Type | Mandatory| Description | | -------- | -------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\\> | Yes | Callback used to return the result. | **Error codes** @@ -2305,7 +2450,7 @@ tls.getSignatureAlgorithms((err, data) => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(): Promise\> +getSignatureAlgorithms(): Promise\\> Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. @@ -2315,7 +2460,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T | Type | Description | | ---------------------- | -------------------- | -| Promise\> | Promise used to return the result.| +| Promise\\> | Promise used to return the result.| **Error codes** @@ -2328,7 +2473,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ```js tls.getSignatureAlgorithms().then(data => { - console.log(data); + console.log("getSignatureAlgorithms success" + data); }).catch(err => { console.error(err); }); @@ -2336,7 +2481,7 @@ tls.getSignatureAlgorithms().then(data => { ### send9+ -send(data: string, callback: AsyncCallback\): void +send(data: string, callback: AsyncCallback\): void Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. @@ -2347,7 +2492,7 @@ Sends a message to the server after a TLSSocket connection is established. This | Name | Type | Mandatory| Description | | -------- | -----------------------------| ---- | ---------------| | data | string | Yes | Data content of the message to send. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2374,7 +2519,7 @@ tls.send("xxxx", (err) => { ### send9+ -send(data: string): Promise\ +send(data: string): Promise\ Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result. @@ -2401,7 +2546,7 @@ Sends a message to the server after a TLSSocket connection is established. This | Type | Description | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** @@ -2415,7 +2560,7 @@ tls.send("xxxx").then(() =>{ ### close9+ -close(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. @@ -2425,7 +2570,7 @@ Closes a TLSSocket connection. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -----------------------------| ---- | ---------------| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2450,7 +2595,7 @@ tls.close((err) => { ### close9+ -close(): Promise\ +close(): Promise\ Closes a TLSSocket connection. This API uses a promise to return the result. @@ -2460,7 +2605,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result. | Type | Description | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2491,7 +2636,7 @@ Defines TLS connection options. | -------------- | ------------------------------------- | --- |-------------- | | address | [NetAddress](#netaddress) | Yes | Gateway address. | | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| -| ALPNProtocols | Array\ | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | +| ALPNProtocols | Array\ | No| Application Layer Protocol Negotiation (ALPN) protocols. | ## TLSSecureOptions9+ @@ -2501,11 +2646,11 @@ Defines TLS security options. The CA certificate is mandatory, and other paramet | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------ | --- |----------------------------------- | -| ca | string \| Array\ | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| +| ca | string \| Array\ | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| | cert | string | No| Digital certificate of the local client. | | key | string | No| Private key of the local digital certificate. | -| passwd | string | No| Password for reading the private key. | -| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. | +| password | string | No| Password for reading the private key. | +| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. | | useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | | signatureAlgorithms | string | No| Signing algorithm used during communication. | | cipherSuite | string | No| Cipher suite used during communication. | diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md index 2896c163a408b3ca5625aee1ccc13379ba89e95d..e0acf1c2ba47df2555dd9812d655e1fb15f777e7 100644 --- a/en/application-dev/reference/apis/js-apis-system-app.md +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -199,7 +199,7 @@ Defines the application response information. ## ScreenOnVisible(deprecated) -screenOnVisible(options?: ScreenOnVisibleOptions) +screenOnVisible(options?: ScreenOnVisibleOptions): void Defines whether to keep the application visible when the screen is woken up. diff --git a/en/application-dev/reference/apis/js-apis-system-bluetooth.md b/en/application-dev/reference/apis/js-apis-system-bluetooth.md index c65aef6079cb393917d7f8a44ef9d62de5e49478..ff04cbb9845aa63f7a5bb7ac12104e485e5991e9 100644 --- a/en/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -1,7 +1,7 @@ # @system.bluetooth (Bluetooth) -> **NOTE**
+> **NOTE** > > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.bluetooth`](js-apis-bluetooth.md). > @@ -19,11 +19,10 @@ import bluetooth from '@system.bluetooth'; Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes system resources. Call [bluetooth.stopBLEScan](#bluetoothstopblescanobject) to stop the scan after a BLE device is detected and connected. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION - **System capability**: SystemCapability.Communication.Bluetooth.Lite **Parameters** + **Table 1** StartBLEScanOptions | Name| Type| Mandatory| Description| @@ -42,7 +41,7 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys console.log('call bluetooth.startBLEScan success.'); }, fail(code, data) { - console.log('call bluetooth.startBLEScan failed, code: ${code}, data: ${data}.'); + console.log('call bluetooth.startBLEScan failed, code:' + code + ', data:' + data); }, complete() { console.log('call bluetooth.startBLEScan complete.'); @@ -55,11 +54,10 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLEScan(OBJECT)](#bluetoothstartblescanobject) in pairs. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION - **System capability**: SystemCapability.Communication.Bluetooth.Lite **Parameters** + **Table 2** StopBLEScanOptions | Name| Type| Mandatory| Description| @@ -76,7 +74,7 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE console.log('call bluetooth.stopBLEScan success.'); }, fail(data, code) { - console.log('call bluethooth.stopBLEScan fail, code: ${code}, data: ${data}.'); + console.log('call bluethooth.stopBLEScan fail, code:' + code + ', data:' + data); }, complete() { console.log('call bluethooth.stopBLEScan complete.'); @@ -89,8 +87,6 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE Subscribes to the newly detected BLE device. If this API is called multiple times, the last call takes effect. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION - **System capability**: SystemCapability.Communication.Bluetooth.Lite **Parameters** @@ -122,10 +118,10 @@ Subscribes to the newly detected BLE device. If this API is called multiple time ``` bluetooth.subscribeBLEFound({ success(data) { - console.log('Called bluetooth.subscribeBLEFound successsully, data: ${data}.'); + console.log('call bluetooth.subscribeBLEFound success, data: ${data}.'); }, fail(data, code) { - console.log('Failed to call bluetooth.startBLEScan, data: ${data}, code: ${code}.'); + console.log('call bluetooth.startBLEScan failed, code:' + code + ', data:' + data); } }); ``` @@ -135,8 +131,6 @@ Subscribes to the newly detected BLE device. If this API is called multiple time Unsubscribes from the newly detected devices. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION - **System capability**: SystemCapability.Communication.Bluetooth.Lite **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index dddb6a685f00a8a5a1829e489d43af4a198bdffa..b99f72e1fb59bd6af33a0bd5f7cc090fc6fc1222 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,9 +1,9 @@ -# @system.cipher (Cipher Algorithm) +# @system.cipher (Cipher Algorithm) > **NOTE** > -> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs provided by this module are deprecated since API version 9. You are advised to use [cryptoFramework-Cipher](js-apis-cryptoFramework.md#Cipher). ## Modules to Import @@ -18,9 +18,10 @@ Defines the response to the cipher interface called. **System capability**: SystemCapability.Security.Cipher -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | -| text | string | Yes | Response content.| +| Name| Type | Readable| Writable|Description | +| ------ | ------ | ---- | ---- | ------------ | +| text | string | Yes | No | Response content.| + ## CipherRsaOptions @@ -74,39 +75,39 @@ Encrypts or decrypts data using RSA. **Example** ```js -export default { - rsa() { - cipher.rsa({ - // Encrypt data. - action: 'encrypt', - // Text to be encrypted. - text: 'hello', - // Base64-encoded public key used for encryption. - key: - 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' + - '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' + +export default { + rsa() { + cipher.rsa({ + // Encrypt data. + action: 'encrypt', + // Text to be encrypted. + text: 'hello', + // Base64-encoded public key used for encryption. + key: + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' + + '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' + '+Enz0RzmVFh/4yk6lmqRzuEFQqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBw\n' + - 'jBpApTJ3TeneOo6Z5QIDAQAB', - success: function(data) { - console.log(`Handling successful:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); + 'jBpApTJ3TeneOo6Z5QIDAQAB', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); - cipher.rsa({ - // Decrypt data. - action: 'decrypt', - // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". - text: + }); + cipher.rsa({ + // Decrypt data. + action: 'decrypt', + // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". + text: 'EPeCFPib6ayKbA0M6oSywARvFZ8dFYfjQv3nY8ikZGtS9UHq2sLPvAfpeIzggSiCxqbWeCftP1XQ\n' + 'Sa+jEpzFlT1qoSTunBbrYzugPTajIJDTg6R1IRsF/J+mmakn0POVPvi4jCo9wqavB324Bx0Wipnc\n' + - 'EU5WO0oBHo5l4x6dTpU=', - // Base64-encoded private key used for decryption. - key: + 'EU5WO0oBHo5l4x6dTpU=', + // Base64-encoded private key used for decryption. + key: 'MIICXgIBAAKBgQCx414QSP3RsYWYzf9mkBMiBAXo6S7Lpva1fKlcuVxjoFC1iMnz\n' + 'D4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ+Enz0RzmVFh/4yk6lmqRzuEF\n' + 'QqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBwjBpApTJ3TeneOo6Z5QIDAQAB\n' + @@ -118,18 +119,18 @@ export default { 'PKoljdXmJeS6rGgzGibstuHLrP3tcIho4+0CQD3ZFWzF/xq0jxKlrpWhnJuNCRfE\n' + 'oO6e9yNvVA8J/5oEDSOcmqSNIp4+RhbUx8InUxnCG6Ryv5aSFu71pYcKrPkCQQCL\n' + 'RUGcm3ZGTnslduB0knNF+V2ndwzDUQ7P74UXT+PjurTPhujFYiuxCEd6ORVnEOzG\n' + - 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + + 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + '8GfqIdUNf+aCG5TZK/kXBF1sqcsi7jXMAf4jBlejVbSVZg==', - success: function(data) { - console.log(`Handling successful:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); - } - }); + } + }); } } ``` @@ -152,48 +153,48 @@ Encrypts or decrypts data using AES. **Example** ```js -export default { - aes() { - cipher.aes({ - // Encrypt data. - action: 'encrypt', - // Text to be encrypted. - text: 'hello', +export default { + aes() { + cipher.aes({ + // Encrypt data. + action: 'encrypt', + // Text to be encrypted. + text: 'hello', // Base64-encoded key. - key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', - transformation: 'AES/CBC/PKCS5Padding', - ivOffset: '0', - ivLen: '16', - success: function(data) { - console.log(`Handling successful:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); - cipher.aes({ - // Decrypt data. - action: 'decrypt', - // Text to be decrypted, which is binary text encoded in Base64. - text: '1o0kf2HXwLxHkSh5W5NhzA==', + }); + cipher.aes({ + // Decrypt data. + action: 'decrypt', + // Text to be decrypted, which is binary text encoded in Base64. + text: '1o0kf2HXwLxHkSh5W5NhzA==', // Base64-encoded key. - key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', - transformation: 'AES/CBC/PKCS5Padding', - ivOffset: '0', - ivLen: '16', - success: function(data) { - console.log(`Handling successful:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.aes encryption failed ### ${code}:${data}`); + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.aes encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); + }); } } diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md index 934ceb020412a18c64499de1cb0ef1593ace2e50..ddc277722b452b8dca63eb50972d9d1f4448726d 100644 --- a/en/application-dev/reference/apis/js-apis-system-configuration.md +++ b/en/application-dev/reference/apis/js-apis-system-configuration.md @@ -50,4 +50,3 @@ Defines attributes of the current locale. | language | string | Yes | No | Language, for example, **zh**.| | countryOrRegion | string | Yes | No | Country or region, for example, **CN** or **US**.| | dir | string | Yes | No | Text layout direction. The value can be:
- **ltr**: from left to right
- **rtl**: from right to left| -| unicodeSetting5+ | string | Yes | No | Unicode language key set determined by the locale. If current locale does not have a specific key set, an empty set is returned.
For example, **{"nu":"arab"}** indicates that current locale uses Arabic numerals.| diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index 140e3bd3d317eefd941515144c1439f8f43bf8d6..7d03495284b4a0a805d1b90b0c46eaf1997200e9 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -70,10 +70,10 @@ export default { console.log('success get location data. latitude:' + data.latitude); }, fail: function(data, code) { - console.log('fail to get location. code:' + code + ', data:' + data); - }, + console.log('fail to get location. code:' + code + ', data:' + data); + } }); - }, + } } ``` @@ -192,8 +192,8 @@ Cancels listening to the geographic location. ``` export default { unsubscribe() { - geolocation.unsubscribe(); - }, + geolocation.unsubscribe(); + } } ``` diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index 91b35f9b29ce4a18b32e19741b14337322ab00bf..0f014e6822dc9b257a7b0eaa6e802b6f7f758110 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,7 +1,7 @@ # @system.notification (Notification) > **NOTE** -> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [@ohos.notification](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,22 +17,22 @@ import notification from '@system.notification'; **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable | Writable | Mandatory| Description | -| ----------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | -| bundleName | string | Yes | Yes | Yes | Name of the application bundle to which the notification will be redirected after being clicked. | -| abilityName | string | Yes | Yes | Yes | Name of the application ability to which the notification will be redirected after being clicked.| -| uri | string | Yes | Yes | No | URI of the page to be redirected to. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | ------------------------- | +| bundleName | string | Yes | Name of the application bundle to which the notification will be redirected after being clicked. | +| abilityName | string | Yes | Name of the application ability to which the notification will be redirected after being clicked.| +| uri | string | No | URI of the page to be redirected to. | ## ShowNotificationOptions **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable | Writable | Mandatory| Description | -| ------------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | -| contentTitle | string | Yes | Yes | No | Notification title. | -| contentText | string | Yes | Yes | No | Notification content. | -| clickAction | ActionResult | Yes | Yes | No | Action triggered when the notification is clicked. | +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------------- | ---- | ------------------------- | +| contentTitle | string | No | Notification title. | +| contentText | string | No | Notification content. | +| clickAction | ActionResult | No | Action triggered when the notification is clicked. | ## notification.show diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md index 5c562892d8f5d5a99423cb79a19478609612aed6..9644d0fa26cda69a6b035c0ba1e2bcbbc9f933dc 100644 --- a/en/application-dev/reference/apis/js-apis-system-package.md +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -23,8 +23,6 @@ hasInstalled(options: CheckPackageHasInstalledOptions): void Checks whether an application exists, or whether a native application has been installed. -**Required permissions**: none - **System capability**: SystemCapability.BundleManager.BundleFramework **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index db74b6b6c4e725c68f47419997bbecb1362da435..0dc490855181cedbe2199810dd45a28384c75c71 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -5,7 +5,7 @@ For details about the system parameter design principles and definitions, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** -> - The APIs of this module are no longer maintained since API version 9. It is recommended that you use [@ohos.systemParameterV9](js-apis-system-parameterV9.md) instead. +> - The APIs of this module are no longer maintained since API version 9. It is recommended that you use [@ohos.systemParameterEnhance](js-apis-system-parameterEnhance.md) instead. > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. > - Third-party applications cannot use the APIs provided by this module, because system parameters each require specific discretionary access control (DAC) and MAC permissions. diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index 30bfc60e3339b8102fbe6f4a6c5fc1202015da11..ccf4be2ce7e5a660ef1622e90bce2c204634906e 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -8,7 +8,7 @@ The sensors are classified into the following categories based on their function > **NOTE** > > - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.sensor`](js-apis-sensor.md) instead. -> - The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - This module requires hardware support and can only be debugged on real devices. @@ -19,15 +19,9 @@ The sensors are classified into the following categories based on their function import sensor from '@system.sensor'; ``` -## Error Codes - -| Error Code | Description | -| ---- | -------------- | -| 900 | The current device does not support the corresponding sensor.| - ## sensor.subscribeAccelerometer -subscribeAccelerometer(Object): void + subscribeAccelerometer(options: subscribeAccelerometerOptions): void Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -37,23 +31,13 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| ---- | ------ | ------- | -| x | number | Acceleration on the x-axis.| -| y | number | Acceleration on the y-axis.| -| z | number | Acceleration on the z-axis.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| options | [subscribeAccelerometerOptions](#subscribeaccelerometeroptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeAccelerometer({ interval: 'normal', success: function(ret) { @@ -82,13 +66,13 @@ Unsubscribes from data changes of the acceleration sensor. **Example** -``` +```js sensor.unsubscribeAccelerometer(); ``` ## sensor.subscribeCompass -subscribeCompass(Object): void + subscribeCompass(options: SubscribeCompassOptions): void Subscribes to data changes of the compass sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -96,20 +80,13 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the compass sensor data changes.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| --------- | ------ | ---------- | -| direction | number | Direction of the device, in degrees.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeCompassOptions](#subscribecompassoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeCompass({ success: function(ret) { console.log('get data direction:' + ret.direction); @@ -133,13 +110,13 @@ Unsubscribes from data changes of the compass sensor. **Example** -``` +```js sensor.unsubscribeCompass(); ``` ## sensor.subscribeProximity -subscribeProximity(Object): void + subscribeProximity(options: SubscribeProximityOptions): void Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -147,20 +124,13 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ----------------- | -| success | Function | Yes | Called when the proximity sensor data changes.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| -------- | ------ | --------------------- | -| distance | number | Distance between a visible object and the device screen.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeProximityOptions](#subscribeproximityoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeProximity({ success: function(ret) { console.log('get data distance:' + ret.distance); @@ -184,13 +154,13 @@ Unsubscribes from data changes of the proximity sensor. **Example** -``` +```js sensor.unsubscribeProximity(); ``` ## sensor.subscribeLight -sensor.subscribeLight(Object): void + subscribeLight(options: SubscribeLightOptions): void Subscribes to data changes of the ambient light sensor. If this API is called multiple times, the last call takes effect. @@ -198,20 +168,13 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the ambient light sensor data changes| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| --------- | ------ | ------------ | -| intensity | number | Light intensity, in lux.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ---------------------------------- | +| options | [SubscribeLightOptions](#subscribelightoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeLight({ success: function(ret) { console.log('get data intensity:' + ret.intensity); @@ -235,13 +198,13 @@ Unsubscribes from data changes of the ambient light sensor. **Example** -``` +```js sensor.unsubscribeLight(); ``` ## sensor.subscribeStepCounter -subscribeStepCounter(Object): void + subscribeStepCounter(options: SubscribeStepCounterOptions): void Subscribes to data changes of the step counter sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -251,20 +214,13 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the step counter sensor data changes.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| ----- | ------ | --------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------------------- | ---- | -------------------------------------- | +| options | [SubscribeStepCounterOptions](#subscribestepcounteroptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeStepCounter({ success: function(ret) { console.log('get step value:' + ret.steps); @@ -290,14 +246,14 @@ Unsubscribes from data changes of the step counter sensor. **Example** -``` +```js sensor.unsubscribeStepCounter(); ``` ## sensor.subscribeBarometer -subscribeBarometer(Object): void +subscribeBarometer(options: SubscribeBarometerOptions): void Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -305,20 +261,13 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the barometer sensor data changes.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| -------- | ------ | ----------- | -| pressure | number | Pressure, in pascal.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | ---------------------------------- | +| options | [SubscribeBarometerOptions](#subscribebarometeroptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeBarometer({ success: function(ret) { console.log('get data value:' + ret.pressure); @@ -343,14 +292,14 @@ Unsubscribes from data changes of the barometer sensor. **Example** -``` +```js sensor.unsubscribeBarometer(); ``` ## sensor.subscribeHeartRate -subscribeHeartRate(Object): void + subscribeHeartRate(options: SubscribeHeartRateOptions): void Subscribes to data changes of the heart rate sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -360,20 +309,13 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| --------- | ------ | ---- | -| heartRate | number | Heart rate.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeHeartRateOptions](#subscribeheartrateoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeHeartRate({ success: function(ret) { console.log('get heartrate value:' + ret.heartRate); @@ -400,13 +342,13 @@ Unsubscribes from data changes of the heart rate sensor. **Example** -``` +```js sensor.unsubscribeHeartRate(); ``` ## sensor.subscribeOnBodyState -subscribeOnBodyState(Object): void + subscribeOnBodyState(options: SubscribeOnBodyStateOptions): void Subscribes to changes of the wearing state of a wearable device. If this API is called multiple times for the same application, the last call takes effect. @@ -414,20 +356,13 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------- | -| success | Function | Yes | Called when the wearing state changes.| -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------------------- | ---- | ---------------------- | +| options | [SubscribeOnBodyStateOptions](#subscribeonbodystateoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeOnBodyState({ success: function(ret) { console.log('get on-body state value:' + ret.value); @@ -451,13 +386,13 @@ Unsubscribes from changes of the wearing state of a wearable device. **Example** -``` +```js sensor.unsubscribeOnBodyState(); ``` ## sensor.getOnBodyState -getOnBodyState(Object): void + getOnBodyState(options: GetOnBodyStateOptions): void Obtains the wearing state of a wearable device. @@ -465,21 +400,13 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ------------ | -| success | Function | No | Callback upon success.| -| fail | Function | No | Callback upon failure.| -| complete | Function | No | Called when the execution is complete.| - -Return values of the success callback - -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | -------------------------- | +| options | [GetOnBodyStateOptions](#getonbodystateoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.getOnBodyState({ success: function(ret) { console.log('on body state: ' + ret.value); @@ -492,7 +419,7 @@ sensor.getOnBodyState({ ## sensor.subscribeDeviceOrientation6+ -subscribeDeviceOrientation(interval: string, success: (data: DeviceOrientationResponse), fail?: (data: string, code: number)): void + subscribeDeviceOrientation(options: SubscribeDeviceOrientationOptions): void Subscribes to data changes of the device orientation sensor. @@ -502,22 +429,13 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | - - Return values of the success callback -| Name | Type | Description | -| ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| options | [SubscribeDeviceOrientationOptions](#subscribedeviceorientationoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeDeviceOrientation({ interval: 'normal', success: function(ret) { @@ -544,13 +462,13 @@ Unsubscribes from data changes of the device orientation sensor. **Example** -``` +```js sensor.unsubscribeDeviceOrientation(); ``` ## sensor.subscribeGyroscope6+ -subscribeGyroscope(interval: string, success: (data: GyroscopeResponse), fail?: (data: string, code: number)): void + subscribeGyroscope(options: SubscribeGyroscopeOptions): void Subscribes to data changes of the gyroscope sensor. @@ -562,23 +480,13 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | - -Return values of the success callback - -| Name | Type | Description | -| ---- | ------ | --------- | -| x | number | Rotation angular velocity of the X axis.| -| y | number | Rotation angular velocity of the Y axis.| -| z | number | Rotation angular velocity of the Z axis.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | ---------------------------------------------- | +| options | [SubscribeGyroscopeOptions](#subscribegyroscopeoptions) | Yes | Type of data to return.| **Example** -``` +```js sensor.subscribeGyroscope({ interval: 'normal', success: function(ret) { @@ -607,6 +515,253 @@ Unsubscribes from data changes of the gyroscope sensor. **Example** -``` +```js sensor.unsubscribeGyroscope(); ``` + +## subscribeAccelerometerOptions + +Defines the type of data to return for a subscription to the acceleration sensor data. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data. The default value is **normal**. The options are as follows: - **game**: called at an interval of 20 ms, which is applicable to gaming scenarios. - **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios. - **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | [AccelerometerResponse](#accelerometerresponse) | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon an API call failure. | + +## AccelerometerResponse + +Defines the type of data to include in an **AccelerometerResponse** object. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------- | +| x | number | Yes | Acceleration on the x-axis.| +| y | number | Yes | Acceleration on the y-axis.| +| z | number | Yes | Acceleration on the z-axis.| + +## SubscribeCompassOptions + +Defines the type of data to return for a subscription to the compass sensor data. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------- | ---- | ------------------------------ | +| success | [CompassResponse](#compassresponse) | Yes | Called when the compass sensor data changes.| +| fail | Function | No | Callback upon an API call failure. | + +## CompassResponse + +Defines the type of data to include in a **CompassResponse** object. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| direction | number | Yes | Direction of the device, in degrees.| + +## SubscribeProximityOptions + +Defines the type of data to return for a subscription to the proximity sensor data. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------- | ---- | ---------------------------------- | +| success | [ProximityResponse](#proximityresponse) | Yes | Called when the proximity sensor data changes.| +| fail | Function | No | Callback upon an API call failure. | + +## ProximityResponse + +Defines the type of data to include in a **ProximityResponse** object. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------ | +| distance | number | Yes | Distance between a visible object and the device screen.| + +## SubscribeLightOptions + +Defines the type of data to return for a subscription to the ambient light sensor data. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------------------ | +| success | [LightResponse](#lightresponse) | Yes | Called when the ambient light sensor data changes| +| fail | Function | No | Callback upon an API call failure. | + +## LightResponse + +Defines the type of data to include in a **LightResponse** object. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------- | +| intensity | number | Yes | Light intensity, in lux.| + +## SubscribeStepCounterOptions + +Defines the type of data to return for a subscription to the step counter sensor data. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | -------------------------------- | +| success | [StepCounterResponse](#stepcounterresponse) | Yes | Called when the step counter sensor data changes.| +| fail | Function | No | Callback upon an API call failure. | + +## StepCounterResponse + +Defines the type of data to include in a **StepCounterResponse** object. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | -------------------------------- | +| steps | number | Yes | Number of counted steps after the sensor is restarted.| + +## SubscribeBarometerOptions + +Defines the type of data to return for a subscription to the barometer sensor data. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------- | ---- | -------------------------------- | +| success | [BarometerResponse](#barometerresponse) | Yes | Called when the barometer sensor data changes.| +| fail | Function | No | Callback upon an API call failure. | + +## BarometerResponse + +Defines the type of data to include in a **BarometerResponse** object. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| pressure | number | Yes | Pressure, in pascal.| + +## SubscribeHeartRateOptions + +Defines the type of data to return for a subscription to the heart rate sensor data. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------- | ---- | ----------------------------------------------- | +| success | [HeartRateResponse](#heartrateresponse) | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| +| fail | Function | No | Callback upon an API call failure. | + +## HeartRateResponse + +Defines the type of data to include in a **HeartRateResponse** object. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------- | +| heartRate | number | Yes | Heart rate.| + +## SubscribeOnBodyStateOptions + +Defines the type of data to return for a subscription to the wearing state changes. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | -------------------------- | +| success | [OnBodyStateResponse](#onbodystateresponse) | Yes | Called when the wearing state changes.| +| fail | Function | No | Callback upon an API call failure. | + +## OnBodyStateResponse + +Defines the wearing state. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ----- | ------- | ---- | ------------ | +| value | boolean | Yes | Whether the wearable device is worn.| + +## GetOnBodyStateOptions + + Defines the type of data to return for obtaining the wearing state. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------ | +| success | [OnBodyStateResponse](#onbodystateresponse) | No | Callback upon a successful API call.| +| fail | Function | No | Callback upon an API call failure.| +| complete | Function | No | Called when the API call is complete.| + +## SubscribeDeviceOrientationOptions6+ + +Defines the type of data to return for a subscription to the device orientation sensor data. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | [DeviceOrientationResponse](#deviceorientationresponse) | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon an API call failure. | + +## DeviceOrientationResponse6+ + +Defines the type of data to include in a **DeviceOrientationResponse** object. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------------------------------------ | +| alpha | number | Yes | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| +| beta | number | Yes | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| +| gamma | number | Yes | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| + +## SubscribeGyroscopeOptions6+ + +Defines the type of data to return for a subscription to the gyroscope sensor data. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | [GyroscopeResponse](#gyroscoperesponse) | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon an API call failure. | + +## GyroscopeResponse6+ + +Defines the type of data to include in a **GyroscopeResponse** object. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ----------------- | +| x | number | Yes | Rotation angular velocity of the X axis.| +| y | number | Yes | Rotation angular velocity of the Y axis.| +| z | number | Yes | Rotation angular velocity of the Z axis.| diff --git a/en/application-dev/reference/apis/js-apis-system-vibrate.md b/en/application-dev/reference/apis/js-apis-system-vibrate.md index 90dc19e2ffb0c8817f7cc2096dc792d252f8996f..a48f2f453f5c1de2d55e23f7005ea5a28b941684 100644 --- a/en/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/en/application-dev/reference/apis/js-apis-system-vibrate.md @@ -1,13 +1,12 @@ # @system.vibrator (Vibrator) - The **Vibrator** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. Misc devices refer to LED lights and vibrators on devices. LED lights are mainly used for indication (for example, indicating the charging state) and blinking (such as tri-colored lights). Vibrators are mainly used in scenarios such as the alarm clock, power-on/off, and incoming call vibration. > **NOTE** -> - The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.vibrator`](js-apis-vibrator.md) instead. > - This module requires hardware support and can only be debugged on real devices. @@ -21,26 +20,23 @@ import vibrator from '@system.vibrator'; ## vibrator.vibrate -vibrate(Object): void + vibrate(options?: VibrateOptions): void Triggers device vibration. -**System capability**: SystemCapability.Sensors.MiscDevice +**Required permissions**: ohos.permission.VIBRATE -**Required permissions**: ohos.permission.VIBRATE (a system permission) +**System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| mode | string | No| Vibration mode. The value **long** indicates long vibration, and **short** indicates short vibration. The default value is **long**.| -| success | Function | Yes| Called when the vibrator data changes.| -| fail | Function | No| Called when the API call fails.| -| complete | Function | No| Called when the API call is complete.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------- | ---- | ---------- | +| options | [VibrateOptions](#vibrateoptions) | No | Vibration options.| **Example** -``` +```js vibrator.vibrate({ mode: 'short', success: function() { @@ -54,3 +50,18 @@ vibrator.vibrate({ } }); ``` + +## VibrateOptions + +Defines the vibration options. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| mode | string | No | Vibration mode. The value **long** indicates long vibration, and **short** indicates short vibration. The default value is **long**.| +| success | Function | No | Called when the vibrator data changes. | +| fail | Function | No | Called when the API call fails. | +| complete | Function | No | Called when the API call is complete. | diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index a441a39e8bb232fd589a0b03e473890ef6bbbc5f..8773e4c9df7945a5b686601b7ad8f3de3694d2f4 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -64,6 +64,7 @@ function func(args) { console.log("func: " + args); return args; } + let task = new taskpool.Task(func, "this is my first Task"); ``` @@ -116,7 +117,12 @@ function func(args) { return args; } -let value = taskpool.execute(func, 100); +async function taskpoolTest() { + let value = await taskpool.execute(func, 100); + console.log("taskpool result: " + value); +} + +taskpoolTest(); ``` ## taskpool.execute @@ -158,8 +164,14 @@ function func(args) { console.log("func: " + args); return args; } -let task = new taskpool.Task(func, "this is my first Task"); -let value = taskpool.execute(task); + +async function taskpoolTest() { + let task = new taskpool.Task(func, 100); + let value = await taskpool.execute(task); + console.log("taskpool result: " + value); +} + +taskpoolTest(); ``` ## taskpool.cancel @@ -193,9 +205,14 @@ function func(args) { console.log("func: " + args); return args; } -let task = new taskpool.Task(func, "this is first Task"); -let value = taskpool.execute(task); -taskpool.cancel(task); + +async function taskpoolTest() { + let task = new taskpool.Task(func, 100); + let value = await taskpool.execute(task); + taskpool.cancel(task); +} + +taskpoolTest(); ``` ## Additional Information @@ -214,10 +231,18 @@ function func(args) { return args; } -let task = new taskpool.Task(func, "create task, then execute"); -let val1 = taskpool.execute(task); +async function taskpoolTest() { + // taskpool.execute(task) + let task = new taskpool.Task(func, "create task, then execute"); + let val1 = await taskpool.execute(task); + console.log("taskpool.execute(task) result: " + val1); -let val2 = taskpool.execute(func, "execute task by func"); + // taskpool.execute(function) + let val2 = await taskpool.execute(func, "execute task by func"); + console.log("taskpool.execute(function) result: " + val2); +} + +taskpoolTest(); ``` ```js @@ -226,7 +251,7 @@ let val2 = taskpool.execute(func, "execute task by func"); // b.ts export var c = 2000; -// a.ts +// a.ts (in the same directory as b.ts) import { c } from './b' function test(a) { @@ -236,8 +261,16 @@ function test(a) { return a; } -let task = new taskpool.Task(test, "create task, then execute"); -let val1 = taskpool.execute(task); +async function taskpoolTest() { + // taskpool.execute(task) + let task = new taskpool.Task(test, "create task, then execute"); + let val1 = await taskpool.execute(task); + console.log("taskpool.execute(task) result: " + val1); + + // taskpool.execute(function) + let val2 = await taskpool.execute(test, "execute task by func"); + console.log("taskpool.execute(function) result: " + val2); +} -let val2 = taskpool.execute(test, "execute task by func"); +taskpoolTest(); ``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index f1c9ad362175bd709d27bc4c7aec0059b413221e..4521aa0eac78b15b8c5644b53aac44fc59b2f648 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ # @ohos.telephony.data (Cellular Data) -The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > @@ -85,7 +85,7 @@ setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): v Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -98,6 +98,19 @@ This is a system API. | slotId | number | Yes | SIM card slot ID.
**0**: card slot 1
**1**: card slot 2
**-1**: Clears the default configuration.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301001 | SIM card is not activated. | + **Example** ```js @@ -112,7 +125,7 @@ setDefaultCellularDataSlotId(slotId: number): Promise\ Sets the default slot of the SIM card used for mobile data. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -130,6 +143,19 @@ This is a system API. | --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300004 | Do not have sim card. | +| 8300999 | Unknown error code. | +| 8301001 | SIM card is not activated. | + **Example** ```js @@ -251,6 +277,17 @@ Checks whether the cellular data service is enabled. This API uses an asynchrono | -------- | ------------------------ | ---- | ------------------------------------------------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -275,6 +312,17 @@ Checks whether the cellular data service is enabled. This API uses a promise to | ------------------ | ------------------------------------------------------------ | | Promise\ | Promise used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -303,6 +351,17 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | | callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -333,6 +392,17 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | ------------------ | ------------------------------------------------------------ | | Promise\ | Promise used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -350,7 +420,7 @@ enableCellularData(callback: AsyncCallback): void Enables the cellular data service. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -362,6 +432,17 @@ This is a system API. | -------- | --------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -376,7 +457,7 @@ enableCellularData(): Promise Enables the cellular data service. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -388,6 +469,17 @@ This is a system API. | --------------- | ----------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -405,7 +497,7 @@ disableCellularData(callback: AsyncCallback): void Disables the cellular data service. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -417,6 +509,17 @@ This is a system API. | -------- | --------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -431,7 +534,7 @@ disableCellularData(): Promise Disables the cellular data service. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -443,6 +546,17 @@ This is a system API. | --------------- | --------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -460,7 +574,7 @@ enableCellularDataRoaming(slotId: number, callback: AsyncCallback): void Enables the cellular data roaming service. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -473,6 +587,17 @@ This is a system API. | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -487,7 +612,7 @@ enableCellularDataRoaming(slotId: number): Promise Enables the cellular data roaming service. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -505,6 +630,17 @@ This is a system API. | --------------- | ------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -522,7 +658,7 @@ disableCellularDataRoaming(slotId: number, callback: AsyncCallback): void Disables the cellular data roaming service. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -535,6 +671,17 @@ This is a system API. | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -549,7 +696,7 @@ disableCellularDataRoaming(slotId: number): Promise Disables the cellular data roaming service. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -567,6 +714,17 @@ This is a system API. | --------------- | ------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index f555df967ddc3a5f11d498bae739be54d1ad53ad..ce3611111a266910c302c779ee5eadc0b1fdc06c 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -22,8 +22,8 @@ Defines the authentication result. | ------------ | ---------- | ---- | -------------------- | | result | number | Yes | Authentication result. | | token | Uint8Array | No | Token that has passed the user identity authentication.| -| remainAttempts | number | No | Number of remaining authentication times allowed.| -| lockoutDuration | number | No | Time for which the authentication operation is frozen.| +| remainAttempts | number | No | Number of remaining authentication attempts.| +| lockoutDuration | number | No | Lock duration of the authentication operation, in milliseconds.| ## TipInfo9+ diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 21ac9df11df7cabdf260edf97fc5fe17f83871b8..16a80bd27e4c9b89397afcaaa83d098fe91eaa10 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -26,7 +26,7 @@ Formats the specified values and inserts them into the string by replacing the w | Name | Type | Mandatory| Description | | ------- | -------- | ---- | -------------- | | format | string | Yes | String.| -| ...args | Object[] | No | Values to format. The formatted values will be replaced the wildcard in the string. | +| ...args | Object[] | No | Values to format. The formatted values will replace the wildcard in the string. If this parameter is not set, the first parameter is returned by default.| **Return value** @@ -69,6 +69,20 @@ let result = util.errnoToString(errnum); console.log("result = " + result); ``` +**Some error code and message examples** + +| Error Code| Message | +| ------ | -------------------------------- | +| -1 | operation not permitted | +| -2 | no such file or directory | +| -3 | no such process | +| -4 | interrupted system call | +| -5 | i/o error | +| -11 | resource temporarily unavailable | +| -12 | not enough memory | +| -13 | permission denied | +| -100 | network is down | + ## util.callbackWrapper callbackWrapper(original: Function): (err: Object, value: Object )=>void @@ -92,15 +106,14 @@ Calls back an asynchronous function. In the callback, the first parameter indica **Example** ```js - async function promiseFn() { - return Promise.reject('value'); - } - let err = "type err"; - let cb = util.callbackWrapper(promiseFn); - cb((err, ret) => { - console.log(err); - console.log(ret); - }, err) +async function fn() { + return 'hello world'; +} +let cb = util.callbackWrapper(fn); +cb(1, (err, ret) => { + if (err) throw err; + console.log(ret); +}); ``` ## util.promisify9+ @@ -126,24 +139,30 @@ Processes an asynchronous function and returns a promise. **Example** ```js - function aysnFun(str1, str2) { - if (typeof str1 === 'object' && typeof str2 === 'object') { - return str2 - } else { - return str1 - } - } - let newPromiseObj = util.promisify(aysnFun); - newPromiseObj({ err: "type error" }, {value:'HelloWorld'}).then(res => { - console.log(res); - }) +function fun(num, callback) { + if (typeof num === 'number') { + callback(null, num + 3); + } else { + callback("type err"); + } +} + +const addCall = util.promisify(fun); +(async () => { + try { + let res = await addCall(2); + console.log(res); + } catch (err) { + console.log(err); + } +})(); ``` -## util.randomUUID9+ +## util.generateRandomUUID9+ -randomUUID(entropyCache?: boolean): string +generateRandomUUID(entropyCache?: boolean): string -Uses a secure random number generator to generate a random universally unique identifier (UUID) of RFC 4122 version 4. +Uses a secure random number generator to generate a random universally unique identifier (UUID) of the string type in RFC 4122 version 4. **System capability**: SystemCapability.Utils.Lang @@ -162,17 +181,17 @@ Uses a secure random number generator to generate a random universally unique id **Example** ```js - let uuid = util.randomUUID(true); + let uuid = util.generateRandomUUID(true); console.log("RFC 4122 Version 4 UUID:" + uuid); // Output: // RFC 4122 Version 4 UUID:88368f2a-d5db-47d8-a05f-534fab0a0045 ``` -## util.randomBinaryUUID9+ +## util.generateRandomBinaryUUID9+ -randomBinaryUUID(entropyCache?: boolean): Uint8Array +generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array -Uses a secure random number generator to generate a random binary UUID of RFC 4122 version 4. +Uses a secure random number generator to generate a random UUID of the Uint8Array type in RFC 4122 version 4. **System capability**: SystemCapability.Utils.Lang @@ -191,7 +210,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41 **Example** ```js - let uuid = util.randomBinaryUUID(true); + let uuid = util.generateRandomBinaryUUID(true); console.log(JSON.stringify(uuid)); // Output: // 138,188,43,243,62,254,70,119,130,20,235,222,199,164,140,150 @@ -201,7 +220,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41 parseUUID(uuid: string): Uint8Array -Parses a UUID from a string, as described in RFC 4122 version 4. +Converts the UUID of the string type generated by **generateRandomUUID** to the UUID of the **Uint8Array** type generated by **generateRandomBinaryUUID**, as described in RFC 4122 version 4. **System capability**: SystemCapability.Utils.Lang @@ -243,7 +262,7 @@ Formats the specified values and inserts them into the string by replacing the w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | format | string | Yes| String.| -| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| +| ...args | Object[] | No| Values to format. The formatted values will replace the wildcard in the string. If this parameter is not set, the first parameter is returned by default.| **Return value** @@ -361,8 +380,8 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate **Example** ```js -let textDecoder = new util.TextDecoder() -textDecoder.create('utf-8', { ignoreBOM : true }); +let result = util.TextDecoder.create('utf-8', { ignoreBOM : true }) +let retStr = result.encoding ``` ### decodeWithStream9+ diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index f99f74149b06752ec0d1edf51ba5c46e40e3e43e..383bc980e60cbf460db627124b77facff8555751 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -42,6 +42,7 @@ For details about the error codes, see [Vibrator Error Codes](../errorcodes/erro **Example** ```js +import vibrator from '@ohos.vibrator'; try { vibrator.startVibration({ type: 'time', @@ -95,6 +96,7 @@ For details about the error codes, see [Vibrator Error Codes](../errorcodes/erro **Example** ```js +import vibrator from '@ohos.vibrator'; try { vibrator.startVibration({ type: 'time', @@ -132,6 +134,7 @@ Stops vibration in the specified mode. This API uses an asynchronous callback to **Example** ```js +import vibrator from '@ohos.vibrator'; try { // Start vibration at a fixed duration. vibrator.startVibration({ @@ -190,6 +193,7 @@ Stops vibration in the specified mode. This API uses a promise to return the res **Example** ```js +import vibrator from '@ohos.vibrator'; try { // Start vibration at a fixed duration. vibrator.startVibration({ @@ -219,6 +223,213 @@ try { } ``` +## vibrator.stopVibration10+ + +stopVibration(callback: AsyncCallback<void>): void + +Stops vibration in all modes. 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 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the vibration stops, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + + ```js +import vibrator from '@ohos.vibrator'; +try { + // Start vibration at a fixed duration. + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; + } + console.log('Callback returned to indicate a successful vibration.'); + }); +} catch (error) { + console.error('errCode: ' + error.code + ' ,msg: ' + error.message); +} + +try { + // Stop vibration in all modes. + vibrator.stopVibration(function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + return; + } + console.log('Callback returned to indicate successful.'); + }) +} catch (error) { + console.info('errCode: ' + error.code + ' ,msg: ' + error.message); +} + ``` + +## vibrator.stopVibration10+ + +stopVibration(): Promise<void> + +Stops vibration in all modes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +import vibrator from '@ohos.vibrator'; +try { + // Start vibration at a fixed duration. + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.log('Promise returned to indicate a successful vibration'); + }, (error) => { + console.error('error.code' + error.code + 'error.message' + error.message); + }); +} catch (error) { + console.error('errCode: ' + error.code + ' ,msg: ' + error.message); +} + +try { + // Stop vibration in all modes. + vibrator.stopVibration().then(() => { + console.log('Promise returned to indicate a successful vibration.'); + }, (error) => { + console.log('error.code' + error.code + 'error.message' + error.message); + }); +} catch (error) { + console.info('errCode: ' + error.code + ' ,msg: ' + error.message); +} + ``` + +## vibrator.isSupportEffect10+ + +isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void + +Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------ | +| effectId | string | Yes | Vibration effect ID. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | + +**Example** + + ```js +import vibrator from '@ohos.vibrator'; +try { + // Check whether 'haptic.clock.timer' is supported. + vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { + if (err) { + console.error('isSupportEffect failed, error:' + JSON.stringify(err)); + return; + } + console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); + if (state) { + try { + vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission. + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }, (error) => { + if(error) { + console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error)); + } else { + console.log('haptic.clock.timer vibrator success'); + } + }); + } catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); + } + } + }) +} catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); +} + ``` + +## vibrator.isSupportEffect10+ + +isSupportEffect(effectId: string): Promise<boolean> + +Checks whether the passed effect ID is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | +| effectId | string | Yes | Vibration effect ID.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------------------------------------- | +| Promise<boolean> | Promise that returns the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | + +**Example** + + ```js +import vibrator from '@ohos.vibrator'; +try { + // Check whether 'haptic.clock.timer' is supported. + vibrator.isSupportEffect('haptic.clock.timer').then((state) => { + console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); + if (state) { + try { + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }).then(()=>{ + console.log('Promise returned to indicate a successful vibration'); + }).catch((error)=>{ + console.error('Promise returned to indicate a failed vibration:' + JSON.stringify(error)); + }); + } catch (error) { + console.error('exception in, error:' + JSON.stringify(error)); + } + } + }, (error) => { + console.error('isSupportEffect failed, error:' + JSON.stringify(error)); + }) +} catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); +} + ``` + ## EffectId Describes the preset vibration effect ID. diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index e8d51f5b1c24b57ecabb1de9341abdac99200e82..28866930fd3a2474f9c0799b9b0f00b9d12006ee 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -14,7 +14,7 @@ The **wallpaper** module is a system service module in OpenHarmony that provides import wallpaper from '@ohos.wallpaper'; ``` -## WallpaperType +## WallpaperType7+ Enumerates the wallpaper types. @@ -26,12 +26,14 @@ Enumerates the wallpaper types. | WALLPAPER_LOCKSCREEN | 1 |Lock screen wallpaper.| -## RgbaColor +## RgbaColor9+ Defines the RGBA color space for the wallpaper. **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| @@ -48,6 +50,8 @@ Obtains the main color information of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| @@ -71,37 +75,6 @@ try { } ``` -## wallpaper.getIdSync9+ - -getIdSync(wallpaperType: WallpaperType): number - -Obtains the ID of the wallpaper of the specified type. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).| - -**Example** - -```js -try { - let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - console.log(`success to getIdSync: ${JSON.stringify(id)}`); -} catch (error) { - console.error(`failed to getIdSync because: ${JSON.stringify(error)}`); -} -``` - ## wallpaper.getMinHeightSync9+ getMinHeightSync(): number @@ -110,6 +83,8 @@ Obtains the minimum height of this wallpaper. **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Return value** | Type| Description| @@ -130,6 +105,8 @@ Obtains the minimum width of this wallpaper. **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Return value** | Type| Description| @@ -142,46 +119,6 @@ Obtains the minimum width of this wallpaper. let minWidth = wallpaper.getMinWidthSync(); ``` -## wallpaper.isChangeAllowed9+ - -isChangeAllowed(): boolean - -Checks whether to allow the application to change the wallpaper for the current user. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| - -**Example** - -```js -let isChangeAllowed = wallpaper.isChangeAllowed(); -``` - -## wallpaper.isUserChangeAllowed9+ - -isUserChangeAllowed(): boolean - -Checks whether the user is allowed to set wallpapers. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| - -**Example** - -```js -let isUserChangeAllowed = wallpaper.isUserChangeAllowed(); -``` - ## wallpaper.restore9+ restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void @@ -192,6 +129,8 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| @@ -221,6 +160,8 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| @@ -253,6 +194,8 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| @@ -306,6 +249,8 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| @@ -350,39 +295,6 @@ imageSource.createPixelMap(opts).then((pixelMap) => { }); ``` -## wallpaper.getFileSync9+ - -getFileSync(wallpaperType: WallpaperType): number; - -Obtains the wallpaper of the specified type. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| - -**Example** - -```js -try { - let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - console.log(`success to getFileSync: ${JSON.stringify(file)}`); -} catch (error) { - console.error(`failed to getFileSync because: ${JSON.stringify(error)}`); -} -``` - ## wallpaper.getImage9+ getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; @@ -449,12 +361,16 @@ wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { }); ``` -## wallpaper.on('colorChange')9+ +## wallpaper.on('colorChange')(deprecated) on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void Subscribes to the wallpaper color change event. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + **System capability**: SystemCapability.MiscServices.Wallpaper **Parameters** @@ -477,12 +393,16 @@ try { } ``` -## wallpaper.off('colorChange')9+ +## wallpaper.off('colorChange')(deprecated) off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void Unsubscribes from the wallpaper color change event. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + **System capability**: SystemCapability.MiscServices.Wallpaper **Parameters** @@ -527,7 +447,7 @@ Obtains the main color information of the wallpaper of the specified type. This > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -558,7 +478,7 @@ Obtains the main color information of the wallpaper of the specified type. This > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -592,7 +512,7 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -623,7 +543,7 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -657,7 +577,7 @@ Obtains the minimum height of this wallpaper. This API uses an asynchronous call > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -687,7 +607,7 @@ Obtains the minimum height of this wallpaper. This API uses a promise to return > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -715,7 +635,7 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -745,7 +665,7 @@ Obtains the minimum width of this wallpaper. This API uses a promise to return t > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -773,7 +693,7 @@ Checks whether to allow the application to change the wallpaper for the current > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -803,7 +723,7 @@ Checks whether to allow the application to change the wallpaper for the current > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -831,7 +751,7 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -861,7 +781,7 @@ Checks whether the user is allowed to set wallpapers. This API uses a promise to > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -889,7 +809,7 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -922,7 +842,7 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -958,7 +878,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -1015,7 +935,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -1074,7 +994,7 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [wallpaper.getFileSync9+](#wallpapergetfilesync9) instead. +> This API is supported since API version 8 and deprecated since API version 9. **Required permissions**: ohos.permission.GET_WALLPAPER @@ -1107,7 +1027,7 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [wallpaper.getFileSync9+](#wallpapergetfilesync9) instead. +> This API is supported since API version 8 and deprecated since API version 9. **Required permissions**: ohos.permission.GET_WALLPAPER @@ -1143,7 +1063,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getImage9+](#wallpapergetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.GET_WALLPAPER @@ -1178,7 +1098,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getImage9+](#wallpapergetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. **Required permissions**: ohos.permission.GET_WALLPAPER diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index dca4d71f55fded097f6d9521b97540bf5eefd433..e0dfa6e3448d5e723fc92feaaf47bf09837d9777 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -12,6 +12,145 @@ The **WantAgent** module provides APIs for creating and comparing **WantAgent** import WantAgent from '@ohos.wantAgent'; ``` +## WantAgent.getWant + +getWant(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the Want in a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ----------------------- | +| agent | [WantAgent](js-apis-wantAgent.md) | Yes | **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the Want.| + +**Example** + +```ts +import WantAgent from '@ohos.wantAgent'; + + +// WantAgent object +let wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; + } + + // getWant callback + function getWantCallback(err, data) { + console.info('==========================>getWantCallback=======================>'); + } + WantAgent.getWant(wantAgent, getWantCallback); +} +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +``` + +## WantAgent.getWant + +getWant(agent: WantAgent): Promise\ + +Obtains the Want in a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------------- | ---- | ------------- | +| agent | [WantAgent](js-apis-wantAgent.md) | Yes | **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the Want.| + +**Example** + +```ts +import WantAgent from '@ohos.wantAgent'; + + +// WantAgent object +let wantAgent; + +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + wantAgent = data; + if (wantAgent) { + WantAgent.getWant(wantAgent).then((data) => { + console.info('==========================>getWantCallback=======================>'); + }); + } +}); +``` + ## WantAgent.getWantAgent getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void @@ -786,135 +925,6 @@ WantAgent.equal(wantAgent1, wantAgent2).then((data) => { }); ``` -## WantAgent.getOperationType9+ - -getOperationType(agent: WantAgent, callback: AsyncCallback\): void; - -Obtains the operation type of a **WantAgent** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------ | ---- | --------------------------------------- | -| agent | WantAgent | Yes | Target **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the operation type.| - -**Example** - -```ts -import WantAgent from '@ohos.wantAgent'; - -// WantAgent object -let wantAgent; - -// WantAgentInfo object -let wantAgentInfo = { - wants: [ - { - deviceId: 'deviceId', - bundleName: 'com.neu.setResultOnAbilityResultTest1', - abilityName: 'com.example.test.EntryAbility', - action: 'action1', - entities: ['entity1'], - type: 'MIMETYPE', - uri: 'key={true,true,false}', - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: '[1, 2, 3]', - mykey3: 'ssssssssssssssssssssssssss', - mykey4: [false, true, false], - mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info('==========================>getWantAgentCallback=======================>'); - wantAgent = data; - if (data) { - WantAgent.getOperationType(wantAgent, (OperationType) => { - console.log('----------- getOperationType ----------, OperationType: ' + OperationType); - }) - } -}); -``` - -## WantAgent.getOperationType9+ - -getOperationType(agent: WantAgent): Promise\; - -Obtains the operation type of a **WantAgent** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | --------- | ---- | ------------- | -| agent | WantAgent | Yes | Target **WantAgent** object.| - -**Return value** - -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the operation type.| - -**Example** - -```ts -import WantAgent from '@ohos.wantAgent'; - -// WantAgent object -let wantAgent; - -// WantAgentInfo object -let wantAgentInfo = { - wants: [ - { - deviceId: 'deviceId', - bundleName: 'com.neu.setResultOnAbilityResultTest1', - abilityName: 'com.example.test.EntryAbility', - action: 'action1', - entities: ['entity1'], - type: 'MIMETYPE', - uri: 'key={true,true,false}', - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: '[1, 2, 3]', - mykey3: 'ssssssssssssssssssssssssss', - mykey4: [false, true, false], - mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info('==========================>getWantAgentCallback=======================>'); - wantAgent = data; - WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); - }).catch((err) => { - console.log('getOperationType fail, err: ' + err); - }) -}); -``` - ## WantAgentFlags **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 2b2fa3af70da2fd1725ef0221b8fd7cf5654f531..6319fda995850708da44bec6c7d00dc158193516 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,10 +1,9 @@ -# @ohos.net.webSocket (WebSocket Connection) +# # @ohos.net.webSocket (WebSocket Connection) -The **webSocket** module implements WebSocket connection management and operation. - -> **NOTE**
-> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** > +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. @@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a import webSocket from '@ohos.net.webSocket'; ``` -## Complete Example +## Examples ```js import webSocket from '@ohos.net.webSocket'; @@ -37,7 +36,7 @@ ws.on('open', (err, value) => { }); ws.on('message', (err, value) => { console.log("on message, message:" + value); - // When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server. + // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server. if (value === 'bye') { ws.close((err, value) => { if (!err) { @@ -49,7 +48,7 @@ ws.on('message', (err, value) => { } }); ws.on('close', (err, value) => { - console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); + console.log("on close, code is " + value.code + ", reason is " + value.reason); }); ws.on('error', (err) => { console.log("on error, error:" + JSON.stringify(err)); @@ -71,7 +70,7 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | | :---------------------------------- | :----------------------------------------------------------- | @@ -94,7 +93,7 @@ connect\(url: string, callback: AsyncCallback\): void Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -105,6 +104,12 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL | url | string | Yes | URL for establishing a WebSocket connection.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -127,7 +132,7 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback< Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -139,6 +144,12 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke | options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -166,7 +177,7 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke | url | string | Yes | URL for establishing a WebSocket connection. | | options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -203,7 +221,7 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback\): void Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -214,6 +232,13 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac | data | string \| ArrayBuffer 8+ | Yes | Data to send.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -237,7 +262,7 @@ send\(data: string | ArrayBuffer\): Promise Sends data through a WebSocket connection. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -247,12 +272,19 @@ Sends data through a WebSocket connection. This API uses a promise to return the | ------ | ------ | ---- | ------------ | | data | string \| ArrayBuffer 8+ | Yes | Data to send.| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -275,7 +307,7 @@ close\(callback: AsyncCallback\): void Closes a WebSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return | -------- | ------------------------ | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -306,7 +345,7 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -317,6 +356,13 @@ Closes a WebSocket connection carrying specified options such as **code** and ** | options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -341,7 +387,7 @@ close\(options?: WebSocketCloseOptions\): Promise Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -351,12 +397,19 @@ Closes a WebSocket connection carrying specified options such as **code** and ** | ------- | --------------------- | ---- | ----------------------------------------------------- | | options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -406,7 +459,7 @@ off\(type: 'open', callback?: AsyncCallback\): void Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -437,7 +490,7 @@ on\(type: 'message', callback: AsyncCallback\): void Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). **System capability**: SystemCapability.Communication.NetStack @@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API | type | string | Yes | Event type.
**message**: event indicating that a message has been received from the server.| | callback | AsyncCallback\8+
\> | Yes | Callback used to return the result. | - **Example** ```js @@ -466,7 +518,7 @@ off\(type: 'message', callback?: AsyncCallback\): void Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. @@ -507,7 +559,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); ws.on('close', (err, value) => { - console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); + console.log("on close, code is " + value.code + ", reason is " + value.reason); }); ``` @@ -518,7 +570,7 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -530,7 +582,6 @@ Disables listening for the **close** events of a WebSocket connection. This API | type | string | Yes | Event type.
**close**: event indicating that a WebSocket connection has been closed.| | callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. | - **Example** ```js @@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u | type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -571,7 +621,7 @@ off\(type: 'error', callback?: ErrorCallback\): void Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -621,8 +671,8 @@ You can customize the result codes sent to the server. The result codes in the f | Value | Description | | :-------- | :----------------- | -| 1000 | Normally closed | -| 1001 | Connection closed by the server | -| 1002 | Incorrect protocol | -| 1003 | Data unable to be processed| -| 1004~1015 | Reserved | +| 1000 | Normally closed. | +| 1001 | Connection closed by the server. | +| 1002 | Incorrect protocol. | +| 1003 | Data unable to be processed.| +| 1004~1015 | Reserved. | diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 13e7a03a329495c89a64b8f21f08891aa23f4858..d20a81f9e2b278fc2095fdd32203cfc3761c4f06 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -2,7 +2,7 @@ # @ohos.web.webview (Webview) -The **Webview** module provides APIs for web control. +The **Webview** module provides APIs for web control. It can be used with the **[](../arkui-ts/ts-basic-components-web.md)** component, which can be used to display web pages. > **NOTE** > @@ -20,7 +20,7 @@ The **Webview** module provides APIs for web control. import web_webview from '@ohos.web.webview'; ``` -### once +## once once(type: string, callback: Callback\): void @@ -43,7 +43,7 @@ import web_webview from '@ohos.web.webview' web_webview.once("webInited", () => { console.log("setCookie") - web_webview.WebCookieManager.setCookie("www.example.com", "a=b") + web_webview.WebCookieManager.setCookie("https://www.example.com", "a=b") }) @Entry @@ -245,6 +245,44 @@ export default class EntryAbility extends UIAbility { } ``` +### setHttpDns10+ + +static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void + +Sets how the \ component uses HTTPDNS for DNS resolution. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description| +| ------------------ | ------- | ---- | ------------- | +| secureDnsMode | [SecureDnsMode](#securednsmode) | Yes | Mode in which HTTPDNS is used.| +| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| + +**Example** + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + try { + web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.Auto, "https://example1.test") + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` + ### Creating an Object ```ts @@ -379,12 +417,12 @@ struct WebComponent { } }) Web({ src: 'www.example.com', controller: this.controller }) - .webDebuggingAccess(true) } } } ``` +Example of loading local web pages: ```ts // xxx.ets import web_webview from '@ohos.web.webview' @@ -399,7 +437,7 @@ struct WebComponent { Button('loadUrl') .onClick(() => { try { - // The URL to be loaded is of the Resource type. + // Load a local resource file through $rawfile. this.controller.loadUrl($rawfile('xxx.html')); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -411,6 +449,32 @@ struct WebComponent { } ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through the resource protocol. + this.controller.loadUrl("resource://rawfile/xxx.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ```html @@ -479,7 +543,34 @@ struct WebComponent { } ``` -### accessforward +Example of loading local resource: +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + updataContent: string = '
image -- end
' + + build() { + Column() { + Button('loadData') + .onClick(() => { + try { + this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### accessForward accessForward(): boolean @@ -1606,7 +1697,7 @@ struct WebComponent { .onClick(() => { try { if (this.ports && this.ports[1]) { - this.ports[1].postMessageEvent("this.sendFromEts"); + this.ports[1].postMessageEvent(this.sendFromEts); } else { console.error(`ports is null, Please initialize first`); } @@ -1648,7 +1739,7 @@ var output = document.querySelector('.output'); window.addEventListener('message', function (event) { if (event.data == '__init_port__') { if (event.ports[0] != null) { - The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. + h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function (event) { // 2. Receive the message sent from the eTS side. var msg = 'Got message from ets:'; @@ -3167,6 +3258,358 @@ struct WebComponent { } ``` +### getCertificate10+ + +getCertificate(): Promise> + +Obtains the certificate information of the current website. When the \ component is used to load an HTTPS website, SSL certificate verification is performed. This API uses a promise to return the [X.509 certificate](./js-apis-cert.md) of the current website. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ---------- | --------------------------------------------- | +| Promise> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +function Uint8ArrayToString(dataArray) { + var dataString = '' + for (var i = 0; i < dataArray.length; i++) { + dataString += String.fromCharCode(dataArray[i]) + } + return dataString +} + +function ParseX509CertInfo(x509CertArray) { + let res: string = 'getCertificate success: len = ' + x509CertArray.length; + for (let i = 0; i < x509CertArray.length; i++) { + res += ', index = ' + i + ', issuer name = ' + + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' + + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' + + x509CertArray[i].getNotBeforeTime() + + ', valid end = ' + x509CertArray[i].getNotAfterTime() + } + return res +} + +@Entry +@Component +struct Index { + // outputStr displays debug information on the UI. + @State outputStr: string = '' + webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Row() { + Column() { + List({space: 20, initialIndex: 0}) { + ListItem() { + Button() { + Text('load bad ssl') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + // Load an expired certificate website and view the obtained certificate information. + this.webviewCtl.loadUrl('https://expired.badssl.com') + }) + .height(50) + } + + ListItem() { + Button() { + Text('load example') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + //Load an HTTPS website and view the certificate information of the website. + this.webviewCtl.loadUrl('https://www.example.com') + }) + .height(50) + } + + ListItem() { + Button() { + Text('getCertificate Promise') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + try { + this.webviewCtl.getCertificate().then(x509CertArray => { + this.outputStr = ParseX509CertInfo(x509CertArray); + }) + } catch (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } + }) + .height(50) + } + + ListItem() { + Button() { + Text('getCertificate AsyncCallback') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + try { + this.webviewCtl.getCertificate((error, x509CertArray) => { + if (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } else { + this.outputStr = ParseX509CertInfo(x509CertArray); + } + }) + } catch (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } + }) + .height(50) + } + } + .listDirection(Axis.Horizontal) + .height('10%') + + Text(this.outputStr) + .width('100%') + .fontSize(10) + + Web({ src: 'https://www.example.com', controller: this.webviewCtl }) + .fileAccess(true) + .javaScriptAccess(true) + .domStorageAccess(true) + .onlineImageAccess(true) + .onPageEnd((e) => { + this.outputStr = 'onPageEnd : url = ' + e.url + }) + .onSslErrorEventReceive((e) => { + // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. + e.handler.handleConfirm() + }) + .width('100%') + .height('70%') + } + .height('100%') + } + } +} +``` + +### getCertificate10+ + +getCertificate(callback: AsyncCallback>): void + +Obtains the certificate information of the current website. When the \ component is used to load an HTTPS website, SSL certificate verification is performed. This API uses an asynchronous callback to return the [X.509 certificate](./js-apis-cert.md) of the current website. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback> | Yes | Callback used to obtain the X.509 certificate array of the current HTTPS website.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +function Uint8ArrayToString(dataArray) { + var dataString = '' + for (var i = 0; i < dataArray.length; i++) { + dataString += String.fromCharCode(dataArray[i]) + } + return dataString +} + +function ParseX509CertInfo(x509CertArray) { + let res: string = 'getCertificate success: len = ' + x509CertArray.length; + for (let i = 0; i < x509CertArray.length; i++) { + res += ', index = ' + i + ', issuer name = ' + + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' + + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' + + x509CertArray[i].getNotBeforeTime() + + ', valid end = ' + x509CertArray[i].getNotAfterTime() + } + return res +} + +@Entry +@Component +struct Index { + // outputStr displays debug information on the UI. + @State outputStr: string = '' + webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Row() { + Column() { + List({space: 20, initialIndex: 0}) { + ListItem() { + Button() { + Text('load bad ssl') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + // Load an expired certificate website and view the obtained certificate information. + this.webviewCtl.loadUrl('https://expired.badssl.com') + }) + .height(50) + } + + ListItem() { + Button() { + Text('load example') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + //Load an HTTPS website and view the certificate information of the website. + this.webviewCtl.loadUrl('https://www.example.com') + }) + .height(50) + } + + ListItem() { + Button() { + Text('getCertificate Promise') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + try { + this.webviewCtl.getCertificate().then(x509CertArray => { + this.outputStr = ParseX509CertInfo(x509CertArray); + }) + } catch (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } + }) + .height(50) + } + + ListItem() { + Button() { + Text('getCertificate AsyncCallback') + .fontSize(10) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .onClick(() => { + try { + this.webviewCtl.getCertificate((error, x509CertArray) => { + if (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } else { + this.outputStr = ParseX509CertInfo(x509CertArray); + } + }) + } catch (error) { + this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; + } + }) + .height(50) + } + } + .listDirection(Axis.Horizontal) + .height('10%') + + Text(this.outputStr) + .width('100%') + .fontSize(10) + + Web({ src: 'https://www.example.com', controller: this.webviewCtl }) + .fileAccess(true) + .javaScriptAccess(true) + .domStorageAccess(true) + .onlineImageAccess(true) + .onPageEnd((e) => { + this.outputStr = 'onPageEnd : url = ' + e.url + }) + .onSslErrorEventReceive((e) => { + // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. + e.handler.handleConfirm() + }) + .width('100%') + .height('70%') + } + .height('100%') + } + } +} +``` + +### setAudioMuted + +setAudioMuted(mute: boolean): void + +Mutes this web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------- | +| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State muted: boolean = false + build() { + Column() { + Button("Toggle Mute") + .onClick(event => { + this.muted = !this.muted + this.controller.setAudioMuted(this.muted) + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebCookieManager Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. @@ -3183,7 +3626,7 @@ Obtains the cookie value corresponding to the specified URL. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | :------------------------ | -| url | string | Yes | URL of the cookie value to obtain.| +| url | string | Yes | URL of the cookie value to obtain. A complete URL is recommended.| **Return value** @@ -3215,7 +3658,7 @@ struct WebComponent { Button('getCookie') .onClick(() => { try { - let value = web_webview.WebCookieManager.getCookie('www.example.com'); + let value = web_webview.WebCookieManager.getCookie('https://www.example.com'); console.log("value: " + value); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -3239,7 +3682,7 @@ Sets a cookie value for the specified URL. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | :------------------------ | -| url | string | Yes | URL of the cookie to set.| +| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| | value | string | Yes | Cookie value to set. | **Error codes** @@ -3267,7 +3710,7 @@ struct WebComponent { Button('setCookie') .onClick(() => { try { - web_webview.WebCookieManager.setCookie('www.example.com', 'a=b'); + web_webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -4135,9 +4578,6 @@ struct WebComponent { try { this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); console.log('num: ' + this.username_password.length); - ForEach(this.username_password, (item) => { - console.log('username_password: ' + item); - }, item => item) } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -4206,7 +4646,7 @@ Checks whether any saved HTTP authentication credentials exist. This API returns | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise. | +| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| **Example** @@ -4771,3 +5211,15 @@ Defines a custom URL scheme. | schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | | isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | | isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | + +## SecureDnsMode10+ + +Describes the mode in which the **\** component uses HTTPDNS. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Value| Description | +| ------------- | -- |----------------------------------------- | +| Off | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| +| Auto | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| +| SecureOnly | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index f8a8d90d0e6eea8ad7a95cb49fe873c7a82d41a5..26fd78b642da4a588bec3a06e12a1b591681da62 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -40,7 +40,7 @@ Enumerates the window types. | TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_POINTER9+ | 14 | Mouse.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| -| TYPE_FLOAT_CAMERA9+ | 15 | Floating camera window.
**Model restriction**: This API can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_FLOAT_CAMERA9+ | 15 | Floating camera window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_DIALOG9+ | 16 | Modal window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_SCREENSHOT9+ | 17 | Screenshot window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| @@ -4671,6 +4671,100 @@ try { ``` +### setWaterMarkFlag10+ + +setWaterMarkFlag(enable: boolean): Promise<void> + +Adds or deletes the watermark flag for this window. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------- | --------- | ------------------------------------------------------------ | +| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | --------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300008 | The operation is on invalid display. | + +**Example** + +```js +try { + let enable = true; + let promise = windowClass.setWaterMarkFlag(enable); + promise.then(()=> { + console.info('Succeeded in setting water mark flag of window.'); + }).catch((err)=>{ + console.error('Failed to set water mark flag of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set water mark flag of window. Cause: ' + JSON.stringify(exception)); +} + +``` + +### setWaterMarkFlag10+ + +setWaterMarkFlag(enable: boolean, callback: AsyncCallback<void>): void + +Adds or deletes the watermark flag for this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | --------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300008 | The operation is on invalid display. | + +**Example** + +```js +try { + let enable = true; + windowClass.setWaterMarkFlag(enable, (err) => { + if (err.code) { + console.error('Failed to set water mark flag of window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting water mark flag of window.'); + }); +} catch (exception) { + console.error('Failed to set water mark flag of window. Cause: ' + JSON.stringify(exception)); +} + +``` + ### show(deprecated) show(callback: AsyncCallback<void>): void @@ -7212,6 +7306,7 @@ controller.animationForShown = (context : window.TransitionContext) => { ); console.info('complete transition end'); }; + ``` ### animationForHidden9+ diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index db8a73c0ff0b29ca6c753073f8ea0d297b19ccb8..88371d4cf32bcbb1686b66f0eaf18e2a4819f3e4 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -82,24 +82,32 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import worker from '@ohos.worker'; // Create a Worker instance. -// In the FA model, the worker script directory and pages directory are at the same level. +// In the FA model, the workers directory is at the same level as the pages directory in the entry module. const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"}); -// In the FA model, the worker script directory and pages directory are at different levels. +// In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js"); -// In the stage model, the worker script directory and pages directory are at the same level. +// In the stage model, the workers directory is at the same level as the pages directory in the entry module. const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); -// In the stage model, the worker script directory and pages directory are at different levels. +// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. const workerStageModel02 = new worker.ThreadWorker('entry/ets/pages/workers/worker.ts'); // For the script URL "entry/ets/workers/worker.ts" in the stage model: -// entry is the value of the name attribute under module in the module.json5 file. -// ets indicates the programming language in use. +// entry is the value of the name attribute under module in the module.json5 file, and ets indicates the programming language in use. +// The script URL is related to the level of the workers directory where the worker file is located and is irrelevant to the file where the new worker is located. + +// In the esmodule build scenario of the stage model, the script URL specification @bundle:bundlename/entryname/ets/workerdir/workerfile is added. +// @bundle is a fixed label, bundlename indicates the bundle name, entryname indicates the module name, and ets indicates the programming language in use. +// workerdir indicates the directory where the worker file is located, and workerfile indicates the worker file name. +// In the stage model, the workers directory is at the same level as the pages directory in the entry module, and bundlename is com.example.workerdemo. +const workerStageModel03 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); +// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module, and bundlename is com.example.workerdemo. +const workerStageModel04 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); ``` -Depending on whether the worker script directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. +Depending on whether the **workers** directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. -(1) The worker script directory and **pages** directory are at the same level. +(1) The **workers** directory and **pages** directory are at the same level. In the FA model: @@ -125,7 +133,7 @@ In the stage model: } ``` -(2) The worker script directory and **pages** directory are at different levels. +(2) The **workers** directory and **pages** directory are at different levels. In the FA model: @@ -178,7 +186,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -213,7 +221,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -248,7 +256,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -282,7 +290,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); }) @@ -316,7 +324,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); // Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -341,7 +349,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.terminate(); ``` @@ -372,7 +380,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.onexit = function(e) { console.log("onexit"); } @@ -412,7 +420,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.onerror = function(e) { console.log("onerror"); } @@ -445,7 +453,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.onmessage = function(e) { // e: MessageEvents. The usage is as follows: // let data = e.data; @@ -480,7 +488,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.onmessageerror= function(e) { console.log("onmessageerror"); } @@ -513,7 +521,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -546,7 +554,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -585,7 +593,16 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); + +workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. +``` + +The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: + +```js +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); + // Usage 1: workerInstance.on("alert_on", (e)=>{ console.log("alert listener callback"); @@ -643,7 +660,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -679,7 +696,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -699,7 +716,7 @@ Removes an event listener for the worker thread. This API provides the same func | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ---------------------------- | | type | string | Yes | Type of the event for which the event listener is to be removed. | -| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. | +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| **Error codes** @@ -712,7 +729,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -751,7 +768,16 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); + +workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. +``` + +The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: + +```js +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); + // Usage 1: workerInstance.on("alert_on", (e)=>{ console.log("alert listener callback"); @@ -768,7 +794,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will not be proactively deleted. +// The event listener created by addEventListener will be always valid and will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -809,7 +835,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -850,7 +876,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; @@ -859,7 +885,7 @@ workerInstance.onmessage = function(e) { ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e){ @@ -898,7 +924,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; @@ -907,7 +933,7 @@ workerInstance.onmessage = function(e) { ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e){ @@ -938,11 +964,11 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e) { @@ -980,12 +1006,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e) { @@ -1023,11 +1049,11 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.workerPort; parentPort.onmessageerror = function(e) { @@ -1068,7 +1094,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -const workerInstance = new worker.ThreadWorker("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1108,11 +1134,11 @@ Defines the event handler to be called when an exception occurs during worker ex ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js") +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort workerPort.onerror = function(e){ @@ -1168,23 +1194,23 @@ A constructor used to create a **Worker** instance. import worker from '@ohos.worker'; // Create a Worker instance. -// In the FA model, the worker script directory and pages directory are at the same level. +// In the FA model, the workers directory is at the same level as the pages directory. const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); -// In the FA model, the worker script directory and pages directory are at different levels. +// In the FA model, the workers directory is at the same level as the parent directory of the pages directory. const workerFAModel02 = new worker.Worker("../workers/worker.js"); -// In the stage model, the worker script directory and pages directory are at the same level. +// In the stage model, the workers directory is at the same level as the pages directory. const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); -// In the stage model, the worker script directory and pages directory are at different levels. +// In the stage model, the workers directory is at the same level as the child directory of the pages directory. const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts'); // For the script URL "entry/ets/workers/worker.ts" in the stage model: // entry is the value of the name attribute under module in the module.json5 file. // ets indicates the programming language in use. ``` -Depending on whether the worker script directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. +Depending on whether the **workers** directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. -(1) The worker script directory and **pages** directory are at the same level. +(1) The **workers** directory and **pages** directory are at the same level. In the FA model: @@ -1207,7 +1233,7 @@ In the stage model: } } ``` -(2) The worker script directory and **pages** directory are at different levels. +(2) The **workers** directory and **pages** directory are at different levels. In the FA model: ```json @@ -1594,6 +1620,14 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. +``` + +The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: + +```js +const workerInstance = new worker.Worker("workers/worker.js"); + // Usage 1: workerInstance.on("alert_on", (e)=>{ console.log("alert listener callback"); @@ -2056,7 +2090,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther ### FA Model ```js -// main.js (The following assumes that the worker script directory and pages directory are at the same level.) +// main.js (The following assumes that the workers directory and pages directory are at the same level.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. const workerInstance = new worker.ThreadWorker("workers/worker.ts"); @@ -2121,7 +2155,7 @@ Configuration of the **build-profile.json5** file: ``` ### Stage Model ```js -// main.js (The following assumes that the worker script directory and pages directory are at different levels.) +// main.js (The following assumes that the workers directory and pages directory are at different levels.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. diff --git a/en/application-dev/reference/arkui-js/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index c46abd3bd91d1acbf99bb15152d3f55f636483eb..16bd3fa15567cd54cb38f7f8835c53c5133b168b 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -1,104 +1,102 @@ # JavaScript-compatible Web-like Development Paradigm -- Universal Component Information - - [Universal Attributes](js-components-common-attributes.md) - - [Universal Styles](js-components-common-styles.md) - - [Universal Events](js-components-common-events.md) - - [Universal Methods](js-components-common-methods.md) - - [Animation Styles](js-components-common-animation.md) - - [Gradient Styles](js-components-common-gradient.md) - - [Transition Styles](js-components-common-transition.md) - - [Media Query](js-components-common-mediaquery.md) - - [Custom Font Styles](js-components-common-customizing-font.md) - - [Atomic Layout](js-components-common-atomic-layout.md) -- Container Components - - [badge](js-components-container-badge.md) - - [dialog](js-components-container-dialog.md) - - [div](js-components-container-div.md) - - [form](js-components-container-form.md) - - [list](js-components-container-list.md) - - [list-item](js-components-container-list-item.md) - - [list-item-group](js-components-container-list-item-group.md) - - [panel](js-components-container-panel.md) - - [popup](js-components-container-popup.md) - - [refresh](js-components-container-refresh.md) - - [stack](js-components-container-stack.md) - - [stepper](js-components-container-stepper.md) - - [stepper-item](js-components-container-stepper-item.md) - - [swiper](js-components-container-swiper.md) - - [tabs](js-components-container-tabs.md) - - [tab-bar](js-components-container-tab-bar.md) - - [tab-content](js-components-container-tab-content.md) -- Basic Components - - [button](js-components-basic-button.md) - - [chart](js-components-basic-chart.md) - - [divider](js-components-basic-divider.md) - - [image](js-components-basic-image.md) - - [image-animator](js-components-basic-image-animator.md) - - [input](js-components-basic-input.md) - - [label](js-components-basic-label.md) - - [marquee](js-components-basic-marquee.md) - - [menu](js-components-basic-menu.md) - - [option](js-components-basic-option.md) - - [picker](js-components-basic-picker.md) - - [picker-view](js-components-basic-picker-view.md) - - [piece](js-components-basic-piece.md) - - [progress](js-components-basic-progress.md) - - [qrcode](js-components-basic-qrcode.md) - - [rating](js-components-basic-rating.md) - - [richtext](js-components-basic-richtext.md) - - [search](js-components-basic-search.md) - - [select](js-components-basic-select.md) - - [slider](js-components-basic-slider.md) - - [span](js-components-basic-span.md) - - [switch](js-components-basic-switch.md) - - [text](js-components-basic-text.md) - - [textarea](js-components-basic-textarea.md) - - [toolbar](js-components-basic-toolbar.md) - - [toolbar-item](js-components-basic-toolbar-item.md) - - [toggle](js-components-basic-toggle.md) - - [web](js-components-basic-web.md) - - [xcomponent](js-components-basic-xcomponent.md) -- Media Components - - [video](js-components-media-video.md) -- Canvas Components - - [canvas](js-components-canvas-canvas.md) - - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) - - [Image](js-components-canvas-image.md) - - [CanvasGradient](js-components-canvas-canvasgradient.md) - - [ImageData](js-components-canvas-imagedata.md) - - [Path2D](js-components-canvas-path2d.md) - - [ImageBitmap](js-components-canvas-imagebitmap.md) - - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) - - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) -- Grid Components - - [Basic Concepts](js-components-grid-basic-concepts.md) - - [grid-container](js-components-grid-container.md) - - [grid-row](js-components-grid-row.md) - - [grid-col](js-components-grid-col.md) -- SVG Components - - [Universal Attributes](js-components-svg-common-attributes.md) - - [svg](js-components-svg.md) - - [rect](js-components-svg-rect.md) - - [circle](js-components-svg-circle.md) - - [ellipse](js-components-svg-ellipse.md) - - [path](js-components-svg-path.md) - - [line](js-components-svg-line.md) - - [polyline](js-components-svg-polyline.md) - - [polygon](js-components-svg-polygon.md) - - [text](js-components-svg-text.md) - - [tspan](js-components-svg-tspan.md) - - [textPath](js-components-svg-textpath.md) - - [animate](js-components-svg-animate.md) - - [animateMotion](js-components-svg-animatemotion.md) - - [animateTransform](js-components-svg-animatetransform.md) - - -- Custom Components - - [Basic Usage](js-components-custom-basic-usage.md) - - [props](js-components-custom-props.md) - - [Style Inheritance](js-components-custom-style.md) - - [slot](js-components-custom-slot.md) - - [Lifecycle Definition](js-components-custom-lifecycle.md) +- Universal Component Information + - [Universal Attributes](js-components-common-attributes.md) + - [Universal Styles](js-components-common-styles.md) + - [Universal Events](js-components-common-events.md) + - [Universal Methods](js-components-common-methods.md) + - [Animation Styles](js-components-common-animation.md) + - [Gradient Styles](js-components-common-gradient.md) + - [Transition Styles](js-components-common-transition.md) + - [Media Query](js-components-common-mediaquery.md) + - [Custom Font Styles](js-components-common-customizing-font.md) + - [Atomic Layout](js-components-common-atomic-layout.md) +- Container Components + - [badge](js-components-container-badge.md) + - [dialog](js-components-container-dialog.md) + - [div](js-components-container-div.md) + - [form](js-components-container-form.md) + - [list](js-components-container-list.md) + - [list-item](js-components-container-list-item.md) + - [list-item-group](js-components-container-list-item-group.md) + - [panel](js-components-container-panel.md) + - [popup](js-components-container-popup.md) + - [refresh](js-components-container-refresh.md) + - [stack](js-components-container-stack.md) + - [stepper](js-components-container-stepper.md) + - [stepper-item](js-components-container-stepper-item.md) + - [swiper](js-components-container-swiper.md) + - [tabs](js-components-container-tabs.md) + - [tab-bar](js-components-container-tab-bar.md) + - [tab-content](js-components-container-tab-content.md) +- Basic Components + - [button](js-components-basic-button.md) + - [chart](js-components-basic-chart.md) + - [divider](js-components-basic-divider.md) + - [image](js-components-basic-image.md) + - [image-animator](js-components-basic-image-animator.md) + - [input](js-components-basic-input.md) + - [label](js-components-basic-label.md) + - [marquee](js-components-basic-marquee.md) + - [menu](js-components-basic-menu.md) + - [option](js-components-basic-option.md) + - [picker](js-components-basic-picker.md) + - [picker-view](js-components-basic-picker-view.md) + - [piece](js-components-basic-piece.md) + - [progress](js-components-basic-progress.md) + - [qrcode](js-components-basic-qrcode.md) + - [rating](js-components-basic-rating.md) + - [richtext](js-components-basic-richtext.md) + - [search](js-components-basic-search.md) + - [select](js-components-basic-select.md) + - [slider](js-components-basic-slider.md) + - [span](js-components-basic-span.md) + - [switch](js-components-basic-switch.md) + - [text](js-components-basic-text.md) + - [textarea](js-components-basic-textarea.md) + - [toolbar](js-components-basic-toolbar.md) + - [toolbar-item](js-components-basic-toolbar-item.md) + - [toggle](js-components-basic-toggle.md) + - [web](js-components-basic-web.md) + - [xcomponent](js-components-basic-xcomponent.md) +- Media Components + - [video](js-components-media-video.md) +- Canvas Components + - [canvas](js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) + - [Image](js-components-canvas-image.md) + - [CanvasGradient](js-components-canvas-canvasgradient.md) + - [ImageData](js-components-canvas-imagedata.md) + - [Path2D](js-components-canvas-path2d.md) + - [ImageBitmap](js-components-canvas-imagebitmap.md) + - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) + - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) +- Grid Components + - [Basic Concepts](js-components-grid-basic-concepts.md) + - [grid-container](js-components-grid-container.md) + - [grid-row](js-components-grid-row.md) + - [grid-col](js-components-grid-col.md) +- SVG Components + - [Universal Attributes](js-components-svg-common-attributes.md) + - [svg](js-components-svg.md) + - [rect](js-components-svg-rect.md) + - [circle](js-components-svg-circle.md) + - [ellipse](js-components-svg-ellipse.md) + - [path](js-components-svg-path.md) + - [line](js-components-svg-line.md) + - [polyline](js-components-svg-polyline.md) + - [polygon](js-components-svg-polygon.md) + - [text](js-components-svg-text.md) + - [tspan](js-components-svg-tspan.md) + - [textPath](js-components-svg-textpath.md) + - [animate](js-components-svg-animate.md) + - [animateMotion](js-components-svg-animatemotion.md) + - [animateTransform](js-components-svg-animatetransform.md) +- Custom Components + - [Basic Usage](js-components-custom-basic-usage.md) + - [props](js-components-custom-props.md) + - [Style Inheritance](js-components-custom-style.md) + - [slot](js-components-custom-slot.md) + - [Lifecycle Definition](js-components-custom-lifecycle.md) - [Dynamic Component Creation](js-components-create-elements.md) - [Data Type Attributes](js-appendix-types.md) diff --git a/en/application-dev/reference/arkui-js/figures/4-0.gif b/en/application-dev/reference/arkui-js/figures/4-0.gif deleted file mode 100644 index 1589d8650fa225626fb8dadf085732f92170e40f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/4-0.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/animate-transform.gif b/en/application-dev/reference/arkui-js/figures/animate-transform.gif deleted file mode 100644 index e83e2ce11234a97242e1f57204b96568ad248d3d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/animate-transform.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/animate-transform2.gif b/en/application-dev/reference/arkui-js/figures/animate-transform2.gif deleted file mode 100644 index 3c65871bb208133129e46956ecee119276a390a5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/animate-transform2.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/animationapi-4.gif b/en/application-dev/reference/arkui-js/figures/animationapi-4.gif deleted file mode 100644 index 294687cdfb0cf7f2ea34f91c87d0a6394b32bff0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/animationapi-4.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125192.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125192.gif new file mode 100644 index 0000000000000000000000000000000000000000..3c5b1fa0343c2e6ec1ebf8592ed769e25fc5b2c4 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125192.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285004.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285004.gif new file mode 100644 index 0000000000000000000000000000000000000000..dcb1ff67a62b1053d3e1c392bbe0535e81771c54 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285004.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167823326.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167823326.gif new file mode 100644 index 0000000000000000000000000000000000000000..78a6830c434d54aab7beba2f171edfb2f8b4e7d9 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167823326.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001229677045.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001229677045.gif new file mode 100644 index 0000000000000000000000000000000000000000..eaf9944676873d49c6ca1ac7110a48413583821c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001229677045.gif differ diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md index e5b7dbf697f485fe49ab8a83eb849457d5c66ea1..ee7d77b8d909a85c416073c74551511de4f5a11c 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -1,6 +1,7 @@ # picker-view > **NOTE** +> > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. The **\** component provides the view that shows an embedded scrollable selector on the screen. diff --git a/en/application-dev/reference/arkui-js/js-components-basic-search.md b/en/application-dev/reference/arkui-js/js-components-basic-search.md index adf32950c2889e99e88d67e28da1b6bfb110f4ee..085a50ad4662a61c7aa4e247e6acffa0be30983b 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-search.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-search.md @@ -1,6 +1,7 @@ # search > **NOTE** +> > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. The **\** component provides an input area for users to search. diff --git a/en/application-dev/reference/arkui-js/js-components-basic-select.md b/en/application-dev/reference/arkui-js/js-components-basic-select.md index e6721685c78744ca4453b50562b59fab220dd767..488a8d1b02e0c4a5a41ca1504fac248b248a7bc4 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-select.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-select.md @@ -1,11 +1,10 @@ # select -The **** component provides a drop-down list that allows users to select among multiple options. - > **NOTE** > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +The **** component provides a drop-down list that allows users to select among multiple options. ## Child Components diff --git a/en/application-dev/reference/arkui-js/js-components-basic-web.md b/en/application-dev/reference/arkui-js/js-components-basic-web.md index 0342d75b5b9183f396ab4fec35c212de5ea9617d..5ce69b6b9762e1afdd3a28fe8895c082f474311c 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-web.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-web.md @@ -1,9 +1,11 @@ # web -The **\** component displays web page content. + >**NOTE** > >This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component displays web page content. + ## Required Permissions ohos.permission.INTERNET, required only for accessing online web pages. diff --git a/en/application-dev/reference/arkui-js/js-components-common-animation.md b/en/application-dev/reference/arkui-js/js-components-common-animation.md index 72969d608a86f4ce8fdf8ad2eb95431e18b93528..572ff5f9aa30d9eb25d8eca25af56511e71b084b 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-animation.md +++ b/en/application-dev/reference/arkui-js/js-components-common-animation.md @@ -1,11 +1,11 @@ # Animation Styles -Components support dynamic rotation, translation, and scaling effects. These effects can be set in the **style** attribute or CSS files. - > **NOTE** > > The initial APIs of this component are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +Components support dynamic rotation, translation, and scaling effects. These effects can be set in the **style** attribute or CSS files. + | Name | Type | Description | | ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | transform-origin | string6+ \| \ \| \ string6+ \| \ \| \ | Origin position of the transformed element. The unit can be px or a percentage (relative to the animation target component). If only one value is specified, the other one is **50%**. The available values for the first string are **left**, **center**, and **right**. The available values for the second string are **top**, **center**, and **bottom**.
Example:
transform-origin: 200px 30%
transform-origin: 100px topt
ransform-origin: center center
Default value: **center center** | diff --git a/en/application-dev/reference/arkui-js/js-components-common-atomic-layout.md b/en/application-dev/reference/arkui-js/js-components-common-atomic-layout.md index ab5c6fb8454469cffb018585cd5f8577bc7f1031..97a704e70013bf65de41999d371c03153761aef3 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-atomic-layout.md +++ b/en/application-dev/reference/arkui-js/js-components-common-atomic-layout.md @@ -1,11 +1,10 @@ # Atomic Layout -The atomic layout implements adaptive layout for screens of different sizes and types. Designers can use the atomic layout to define adaptive rules for elements on UIs of different forms. Developers can use the atomic layout to implement the adaptive UI features matching the design effect for a variety of screens. - > **NOTE** > > This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +The atomic layout implements adaptive layout for screens of different sizes and types. Designers can use the atomic layout to define adaptive rules for elements on UIs of different forms. Developers can use the atomic layout to implement the adaptive UI features matching the design effect for a variety of screens. ## Hiding Components diff --git a/en/application-dev/reference/arkui-js/js-components-common-methods.md b/en/application-dev/reference/arkui-js/js-components-common-methods.md index 3a7d61034f5e8eece95d71ebe9ca2c82556401f7..5945c299f720fa34829fe2eb6cd32b32c9f3278a 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-methods.md +++ b/en/application-dev/reference/arkui-js/js-components-common-methods.md @@ -139,56 +139,46 @@ button{ ```js // xxx.js -import promptAction from '@ohos.promptAction'; -export default{ - data:{ - animation:'', - }, - onInit(){ - }, - onShow(){ - var options = { - duration: 1500, - easing: 'friction', - delay: 500, - fill: 'forwards', - iterations: 2, - direction: 'normal', - }; - var frames = [ - {transform: {translate: '-120px -0px'}, opacity: 0.1, offset: 0.0}, - {transform: {translate: '120px 0px'}, opacity: 1.0, offset: 1.0} - ]; - this.animation = this.$element('idName').animate(frames, options); - // handle finish event - this.animation.onfinish = function(){ - promptAction.showToast({ - message: "The animation is finished." - }); - }; - // handle cancel event - this.animation.oncancel = function(){ - promptAction.showToast({ - message: "The animation is canceled." - }); - }; - // handle repeat event - this.animation.onrepeat = function(){ - promptAction.showToast({ - message: "The animation is repeated." - }); - }; - }, - start(){ - this.animation.play(); - }, - cancel(){ - this.animation.cancel(); - } +export default { + data: { + animation: '', + options: {}, + frames: {} + }, + onInit() { + this.options = { + duration: 1500, + easing: 'friction', + delay: 500, + fill: 'forwards', + iterations: 2, + direction: 'normal', + }; + this.frames = [ + { + transform: { + translate: '-120px -0px' + }, opacity: 0.1, offset: 0.0 + }, + { + transform: { + translate: '120px 0px' + }, opacity: 1.0, offset: 1.0 + } + ]; + }, + + start() { + this.animation = this.$element('idName').animate(this.frames, this.options); + this.animation.play(); + }, + cancel() { + this.animation.cancel(); + } } ``` -![animationapi-4](figures/animationapi-4.gif) +![en-us_image_0000001229677045](figures/en-us_image_0000001229677045.gif) ## getBoundingClientRect diff --git a/en/application-dev/reference/arkui-js/js-components-container-stepper-item.md b/en/application-dev/reference/arkui-js/js-components-container-stepper-item.md index c667c410dc89e77f6ec2e1f0a3bcf9ece2597dc6..c67150bc473949b57c052f6b7e74bb20d3a9e2cc 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-stepper-item.md +++ b/en/application-dev/reference/arkui-js/js-components-container-stepper-item.md @@ -1,10 +1,11 @@ # stepper-item -The **\** component displays a step in the step navigator. This component is the child component of **\**. - > **NOTE** > This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component displays a step in the step navigator. This component is the child component of **\**. + + ## Required Permissions None diff --git a/en/application-dev/reference/arkui-js/js-components-container-swiper.md b/en/application-dev/reference/arkui-js/js-components-container-swiper.md index f607139653a52a1e1edbca359ca60d7224ebcc30..6a16be9d774b42edb9a7fc1ffe57d5d1867ee813 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-swiper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-swiper.md @@ -118,16 +118,19 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. } .swiperContent1{ height: 100%; + width: 100%; justify-content: center; background-color: #007dff; } .swiperContent2{ height: 100%; + width: 100%; justify-content: center; background-color: #ff7500; } .swiperContent3{ height: 100%; + width: 100%; justify-content: center; background-color: #41ba41; } @@ -155,4 +158,4 @@ export default { } ``` -![4-0](figures/4-0.gif) +![en-us_image_0000001167823326](figures/en-us_image_0000001167823326.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-tab-content.md b/en/application-dev/reference/arkui-js/js-components-container-tab-content.md index 09dd135cffdeba9254544bc14f662637aef3c847..aed456e555fc8206ebecf81600a48dc0857c6d16 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-tab-content.md +++ b/en/application-dev/reference/arkui-js/js-components-container-tab-content.md @@ -1,11 +1,10 @@ # tab-content -**** is a child component of **[](js-components-container-tabs.md)** and is used to provide the area for displaying the tab content. By default, its height is such that all the remaining space of the **** component is filled. The child components are arranged horizontally. When **** is used as a child element in a container, its length along the main axis must be specified. Otherwise, it cannot be displayed. - > **NOTE** > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +**** is a child component of **[](js-components-container-tabs.md)** and is used to provide the area for displaying the tab content. By default, its height is such that all the remaining space of the **** component is filled. The child components are arranged horizontally. When **** is used as a child element in a container, its length along the main axis must be specified. Otherwise, it cannot be displayed. **\** does not support page scrolling. If page scrolling is required, consider nesting a list. ## Required Permissions @@ -21,7 +20,7 @@ Supported In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -| Name | Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | scrollable | boolean | No| Whether the tabs can be switched by swiping left or right. The default value is **true**. If this attribute is set to **false**, tab switching is implemented only through the association with **tab-bar**.| diff --git a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md index b6f659f069b4e7c5f6dc6347664552a8c6a82e4d..4759de401d3e60ec49a8434ab27abc0c92e65d34 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md @@ -3,7 +3,7 @@ Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can import a custom component to the host page through **element** as shown in the following code snippet: ```html - +
@@ -12,8 +12,8 @@ Custom components are existing components encapsulated based on service requirem The following is an example of using a custom component with **if-else**, which displays **comp1** when **showComp1** is set to **true** and displays **comp2** otherwise. ```html - - + +
@@ -76,7 +76,7 @@ The following example describes how to import **comp** to the parent component: ```html - +
@@ -125,7 +125,7 @@ In the following example, the child component passes the **text** parameter to t ```html - +
Parent component: {{text}} diff --git a/en/application-dev/reference/arkui-js/js-components-custom-props.md b/en/application-dev/reference/arkui-js/js-components-custom-props.md index c9c496b57842c628eabb96377c8096c6a9cc1f9c..c2c0c64961108bcb9f0e2d965b86883593a20dce 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-props.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-props.md @@ -21,7 +21,7 @@ export default { ```html - +
@@ -57,7 +57,7 @@ In this example, a **\** component is added to display the title. The titl ```html - +
diff --git a/en/application-dev/reference/arkui-js/js-components-custom-slot.md b/en/application-dev/reference/arkui-js/js-components-custom-slot.md index 50c5b9ed0d1ad181567945134be95e0f9c229fed..706268221ec46fd3d18b3c0609229e4c1952efb3 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-slot.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-slot.md @@ -20,7 +20,7 @@ You can use the **\** tag to create a slot inside a custom component to fi The following references the custom component: ```html - +
Content defined in the parent component @@ -45,7 +45,7 @@ When multiple slots are need inside a custom component, you can name them, so th The following references the custom component: ```html - +
Fill in the second slot. diff --git a/en/application-dev/reference/arkui-js/js-components-custom-style.md b/en/application-dev/reference/arkui-js/js-components-custom-style.md index ba8644e3e347e700b523ea0c7f2ab02159faeca7..635c07cc1abe37bf7aa99888cf4efbe77429e02a 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-style.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-style.md @@ -1,6 +1,6 @@ # Style Inheritance -> **NOTE**
+> **NOTE** > > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animate.md b/en/application-dev/reference/arkui-js/js-components-svg-animate.md index e90d520cb36057ac385917e4df3d532c8669e97d..46a636aa4043e95c4c1de83b39e09371396fa0cd 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animate.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animate.md @@ -28,9 +28,9 @@ Not supported | end | <time> | 0 | No| Duration after which the animation ends. The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.| | repeatCount | <number \| indefinite> | 1 | No| Number of times the animation is played. The default value is indefinite. You can set the value to **1** to play the animation only once.| | fill | <freeze \| remove> | remove | No| State when the animation ends.| -| calcMode | <discrete \| linear \| paced \| spline> | linear | No| Interpolation mode of the animation.
**discrete**: The value of **from** directly jumps to the value of **to**.
**linear**: linear.
**paced**: linear. After this value is set, the values of **keyTimes** and **keyPoints** are invalid.
**spline**: user-defined Bessel curve. The spline point is defined in the **keyTimes** attribute, and the control point of each interval is defined by **keySplines**.| -| keyTimes | string | - | No| Start time of the key frame animation. The value ranges from 0 to 1, separated by semicolons (;), for example, **0;0.3;0.8;1**. **keyTimes**, **keySplines**, and **values** are combined to set the key frame animation. The number of **keyTimes** is the same as that of **values**. The number of **keySplines** is the number of **keyTimes** minus 1.| -| keySplines | string | - | No| A set of Bessel control points associated with **keyTimes**. You can define the Bessel curves for each key frame. The curves are separated by semicolons (;). The format of the two controls in the curve is x1 y1 x2 y2. For example, **0.5 0 0.5 1; 0.5 0 0.5 1;0.5 0 0.5 1**.| +| calcMode | <discrete \| linear \| paced \| spline> | linear | No| Interpolation mode of the animation.
**discrete**: The animation directly jumps from the value specified by **from** to the value specified by **to**.
**linear**: Linear interpolation between values is used.
**paced**: Interpolation that produces an even paced change is used. If this value is set, the values of **keyTimes** and **keyPoints** will not take effect.
**spline**: Interpolation is implemented based on a custom Bezier spline. The spline points are defined in the **keyTimes** attribute, and the control points of each interval are defined in the **keySplines** attribute.| +| keyTimes | string | - | No| Start time of the key frame animation. The value is a semicolon-separated list of values ranging from 0 to 1, for example, **0;0.3;0.8;1**. **keyTimes**, **keySplines**, and **values** are combined to set the key frame animation. The number of values defined for **keyTimes** is the same as that for **values**. The number of values defined for **keySplines** is the number of values defined for **keyTimes** minus 1.| +| keySplines | string | - | No| A set of Bezier control points associated with **keyTimes**. You can define the Bezier curves for each key frame, separating them with semicolons (;). The format of the two control points in the curve is x1 y1 x2 y2, for example, **0.5 0 0.5 1; 0.5 0 0.5 1;0.5 0 0.5 1**.| | by | number | - | No| Relative offset value to add to a specified attribute in the animation. The default value of **from** is the original attribute value.| | from | string | - | No| Start value of the attribute to which the animation is applied.
If the **values** attribute has been set, the **from** attribute is invalid.| | to | string | - | No| End value of the attribute to which the animation is applied.
If the **values** attribute has been set, the **to** attribute is invalid.| @@ -76,7 +76,7 @@ Not supported
- +
diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md index d9242543a6fda9398032b299d00cf4cf755edfc9..20d19b53d05cc201c4a258b49ff27552701b5669 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md @@ -91,7 +91,7 @@ The **animate** attributes and the attributes in the following table are support ``` -![animate-transform](figures/animate-transform.gif) +![en-us_image_0000001127285004](figures/en-us_image_0000001127285004.gif) Animation overlay @@ -150,7 +150,7 @@ Animation overlay ``` -![animate-transform2](figures/animate-transform2.gif) +![en-us_image_0000001127125192](figures/en-us_image_0000001127125192.gif) Example of involved components diff --git a/en/application-dev/reference/arkui-js/js-components-svg-circle.md b/en/application-dev/reference/arkui-js/js-components-svg-circle.md index 66e793fe790ccc471f91e271b8ae92163d507ac3..3b486978b5123f47660cc130a5d63d39184b1359 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-circle.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-circle.md @@ -1,11 +1,11 @@ # circle -The **\** component is used to draw circles. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw circles. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-svg-ellipse.md b/en/application-dev/reference/arkui-js/js-components-svg-ellipse.md index 1d790bb7cf468e75dc8cd070e01fd42beddf1574..f678409ea72539da10ed2d3a44b80a269d516846 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-ellipse.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-ellipse.md @@ -1,11 +1,11 @@ # ellipse -The **\** component is used to draw oval shapes. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw oval shapes. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-svg-line.md b/en/application-dev/reference/arkui-js/js-components-svg-line.md index f181199036a0d71e2e26e8a66cc3b9d05527ec04..9215e1dc367fa488d45e1e78d62fc4530c70c882 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-line.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-line.md @@ -1,11 +1,11 @@ # line -The **\** component is used to draw a line. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw a line. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-svg-path.md b/en/application-dev/reference/arkui-js/js-components-svg-path.md index a1e114c49db8f8d608a4137b91fcd50fba9c5453..0cec8074e4892ec1ebc84ff6e90e1dcfcb732f44 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-path.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-path.md @@ -1,10 +1,11 @@ # path -The **\** component is used to draw a path. > **NOTE** -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw a path. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-svg-polygon.md b/en/application-dev/reference/arkui-js/js-components-svg-polygon.md index d747dc84673e72fa6e262509ee77469a3ee6515a..8395e4d4d2cc8462b61231be3f64f9e708787f09 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-polygon.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-polygon.md @@ -1,12 +1,13 @@ # polygon -The **\** component is used to draw a polygon. - > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw a polygon. + + ## Required Permissions None @@ -19,7 +20,7 @@ The following are supported: [\](js-components-svg-animate.md), [\** component is used to draw a polyline. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw a polyline. ## Required Permissions @@ -19,7 +19,7 @@ The following are supported: [\](js-components-svg-animate.md), [\** component is used to draw rectangles and rounded rectangles. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to draw rectangles and rounded rectangles. ## Required Permissions @@ -19,7 +19,7 @@ The following are supported: [\](js-components-svg-animate.md), [\** component is used to display a piece of textual information. - > **NOTE** > @@ -13,6 +11,8 @@ The **\** component is used to display a piece of textual information. > > - Only the default font **sans-serif** is supported. +The **\** component is used to display a piece of textual information. + ## Required Permissions None diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 25736a22dced9dd795af1edd130de06ab02248cf..9b2c8d0277f79df9dc0cc3e59aece289076af677 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -42,6 +42,7 @@ - [Hit Test Control](ts-universal-attributes-hit-test-behavior.md) - [Background Blur](ts-universal-attributes-backgroundBlurStyle.md) - [restoreId](ts-universal-attributes-restoreId.md) + - [Foreground Color](ts-universal-attributes-foreground-color.md) - Gesture Processing - [Gesture Binding Methods](ts-gesture-settings.md) - Basic Gestures @@ -53,6 +54,7 @@ - [SwipeGesture](ts-basic-gestures-swipegesture.md) - [Combined Gestures](ts-combined-gestures.md) - Basic Components + - [AlphabetIndexer](ts-container-alphabet-indexer.md) - [Blank](ts-basic-components-blank.md) - [Button](ts-basic-components-button.md) - [Checkbox](ts-basic-components-checkbox.md) @@ -60,11 +62,15 @@ - [DataPanel](ts-basic-components-datapanel.md) - [DatePicker](ts-basic-components-datepicker.md) - [Divider](ts-basic-components-divider.md) + - [Formcomponent](ts-basic-components-formcomponent.md) - [Gauge](ts-basic-components-gauge.md) - [Image](ts-basic-components-image.md) - [ImageAnimator](ts-basic-components-imageanimator.md) - [LoadingProgress](ts-basic-components-loadingprogress.md) - [Marquee](ts-basic-components-marquee.md) + - [Menu](ts-basic-components-menu.md) + - [MenuItem](ts-basic-components-menuitem.md) + - [MenuItemGroup](ts-basic-components-menuitemgroup.md) - [Navigation](ts-basic-components-navigation.md) - [NavRouter](ts-basic-components-navrouter.md) - [NavDestination](ts-basic-components-navdestination.md) @@ -95,7 +101,6 @@ - [XComponent](ts-basic-components-xcomponent.md) - Container Components - [AbilityComponent](ts-container-ability-component.md) - - [AlphabetIndexer](ts-container-alphabet-indexer.md) - [Badge](ts-container-badge.md) - [Column](ts-container-column.md) - [ColumnSplit](ts-container-columnsplit.md) diff --git a/en/application-dev/reference/arkui-ts/figures/ColoringStrategy_circle.png b/en/application-dev/reference/arkui-ts/figures/ColoringStrategy_circle.png new file mode 100644 index 0000000000000000000000000000000000000000..1ea0edb63c1effab0ff368714baeece62b0cf49f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/ColoringStrategy_circle.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png b/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png index edf91d4844deeee4f997f65d2d88b45bf7ff7f1d..0cf19ef4273d18c84b86582543129906e8720142 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png and b/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378422.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378422.gif deleted file mode 100644 index ac096bd0f149b02d46013420a9c323fe8aa5805a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378422.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif new file mode 100644 index 0000000000000000000000000000000000000000..738e50b17cf1c20514f17034ec08bba1cadf2893 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858415.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858415.png deleted file mode 100644 index 6b2c6040690cebf054da6dbc70c87d14c82be9d6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858415.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138363.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138363.gif deleted file mode 100644 index 3a2f5de773fed90a3c0c058d0b27bc0edd1f1904..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138363.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777774.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777774.png index 60f430b646b45a3e3b16a9bb024e4a14e48bf4d3..24edbed60b52947c5effbba951a6523582603f30 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777774.png and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777774.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777775.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777775.png index 60f430b646b45a3e3b16a9bb024e4a14e48bf4d3..24edbed60b52947c5effbba951a6523582603f30 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777775.png and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777775.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png index 4558b332925757d97d70ee57182c260804629346..24edbed60b52947c5effbba951a6523582603f30 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/foregroundColorInherit.jpg b/en/application-dev/reference/arkui-ts/figures/foregroundColorInherit.jpg new file mode 100644 index 0000000000000000000000000000000000000000..576b20baebaafe45b8e360b2cc1d2aba1a0a9ba1 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/foregroundColorInherit.jpg differ diff --git a/en/application-dev/reference/arkui-ts/figures/foregroundColor_circle.png b/en/application-dev/reference/arkui-ts/figures/foregroundColor_circle.png new file mode 100644 index 0000000000000000000000000000000000000000..1d769ec260258ac57833600a8e3cbda3e985166b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/foregroundColor_circle.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/menu1.png b/en/application-dev/reference/arkui-ts/figures/menu1.png new file mode 100644 index 0000000000000000000000000000000000000000..c431b6e9dd911b7f93b778eb6fb290063bb0338a Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/menu1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/qrcode.png b/en/application-dev/reference/arkui-ts/figures/qrcode.png new file mode 100644 index 0000000000000000000000000000000000000000..762c952314fc6e52bbbc0ae55565422c40d05ff0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/qrcode.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/richText.png b/en/application-dev/reference/arkui-ts/figures/richText.png index 65826de750d037a394178b66805a9d1ffdad374e..d7ae9f6dfaa45c77143700a24addf29371c7cc38 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/richText.png and b/en/application-dev/reference/arkui-ts/figures/richText.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/span.png b/en/application-dev/reference/arkui-ts/figures/span.png new file mode 100644 index 0000000000000000000000000000000000000000..881f4945dac79e31cb9f11216a682110de4efec7 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/span.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md index 36d37c6d5fe1e091128d60ee0ff9f337bd13c818..f22e531ac3a0f8423c9e8de5af520a92d2828d5f 100644 --- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -6,20 +6,21 @@ You can create a property animator to animate certain universal attributes of a > > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description | | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ | -| duration | number | No | Animation duration, in ms.
Default value: **1000**| +| duration | number | No | Animation duration, in ms.
Default value: **1000**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The maximum animation duration on an ArkTS widget is 1000 ms. If the set value exceeds the limit, the value **1000** will be used. | | tempo | number | No | Animation playback speed. A greater value indicates a higher animation playback speed.
The value **0** indicates that no animation is applied.
Default value: **1**| -| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve9+ | No | Animation curve.
Default value: **Curve.Linear** | +| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve9+ | No | Animation curve.
Default value: **Curve.Linear**
Since API version 9, this API is supported in ArkTS widgets. | | delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.
Default value: **0** | | iterations | number | No | Number of times that the animation is played. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| -| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**| -| onFinish | () => void | No | Callback invoked when the animation playback is complete. | +| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**
Since API version 9, this API is supported in ArkTS widgets.| +| onFinish | () => void | No | Callback invoked when the animation playback is complete.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index ecc026e3fd2d4613e5b3fb0e48533e29d6f1a941..967d9a0f35c6e5ee71a4ebe8a09ceaed21305c53 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -2,6 +2,8 @@ ## Color +Since API version 9, this API is supported in ArkTS widgets. + | Color | Value | Illustration | | ------------------------ | -------- | ------------------------------------------------------------ | | Black | 0x000000 | ![en-us_image_0000001219864153](figures/en-us_image_0000001219864153.png) | @@ -19,6 +21,8 @@ ## ImageFit +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | --------- | ------------------------------------------------------------ | | Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | @@ -30,6 +34,8 @@ ## BorderStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ----------------------------------------------- | | Dotted | Dotted border. The radius of a dot is half of **borderWidth**.| @@ -38,6 +44,8 @@ ## LineJoinStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----- | -------------------- | | Bevel | Bevel is used to connect paths.| @@ -46,6 +54,8 @@ ## TouchType +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------------ | | Down | A finger is pressed. | @@ -55,6 +65,8 @@ ## MouseButton +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | ---------------- | | Left | Left button on the mouse. | @@ -66,6 +78,8 @@ ## MouseAction +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | -------------- | | Press | The mouse button is pressed.| @@ -75,6 +89,8 @@ ## Curve +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------------------- | ------------------------------------------------------------ | | Linear | The animation speed keeps unchanged. | @@ -93,6 +109,8 @@ ## AnimationStatus +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | ------------------ | | Initial | The animation is in the initial state. | @@ -102,6 +120,8 @@ ## FillMode +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | --------- | ------------------------------------------------------------ | | None | Before execution, the animation does not apply any styles to the target component. After execution, the animation restores the target component to its default state.| @@ -111,6 +131,8 @@ ## PlayMode +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ---------------- | ------------------------------------------------------------ | | Normal | The animation is played forwards. | @@ -120,6 +142,8 @@ ## KeyType +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description | | ---- | ---------- | | Down | The key is pressed.| @@ -127,6 +151,8 @@ ## KeySource +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | -------------------- | | Unknown | Unknown input device. | @@ -136,16 +162,18 @@ | Name | Description | | -------- | ---------------------- | -| Top | Top edge in the vertical direction. | -| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | -| Bottom | Bottom edge in the vertical direction. | +| Top | Top edge in the vertical direction.
Since API version 9, this API is supported in ArkTS widgets.| +| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9.| +| Bottom | Bottom edge in the vertical direction.
Since API version 9, this API is supported in ArkTS widgets.| | Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9.| -| Start | Start position in the horizontal direction. | -| Middle(deprecated) | Center position in the horizontal direction.
This API is deprecated since API version 9. | -| End | End position in the horizontal direction. | +| Start | Start position in the horizontal direction.
Since API version 9, this API is supported in ArkTS widgets.| +| Middle(deprecated) | Center position in the horizontal direction.
This API is deprecated since API version 9.| +| End | End position in the horizontal direction.
Since API version 9, this API is supported in ArkTS widgets.| ## Week +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | ---------------------- | | Mon | Monday. | @@ -158,6 +186,8 @@ ## Direction +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description | | ---- | ---------------------- | | Ltr | Components are arranged from left to right. | @@ -166,6 +196,8 @@ ## BarState +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description | | ---- | -------------------------------- | | Off | Not displayed. | @@ -174,6 +206,8 @@ ## EdgeEffect +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------------------------------------------ | | Spring | Spring effect. When at one of the edges, the component can move beyond the bounds through touches, and produces a bounce effect when the user releases their finger.| @@ -182,6 +216,8 @@ ## Alignment +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | ---------------- | | TopStart | Top start. | @@ -196,6 +232,8 @@ ## TransitionType +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | -------------------------------------------------- | | All | The transition takes effect in all scenarios.| @@ -204,6 +242,8 @@ ## RelateType +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------------- | | FILL | The current child component is scaled to fill the parent component. | @@ -211,6 +251,8 @@ ## Visibility +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | -------------------------------- | | Hidden | The component is hidden, and a placeholder is used for it in the layout. | @@ -219,6 +261,8 @@ ## LineCapStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | -------------------- | | Butt | The ends of the line are squared off, and the line does not extend beyond its two endpoints.| @@ -227,6 +271,8 @@ ## Axis +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ---------- | ------------ | | Vertical | Vertical direction.| @@ -234,6 +280,8 @@ ## HorizontalAlign +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------ | | Start | Aligned with the start edge in the same direction as the language in use.| @@ -242,6 +290,8 @@ ## FlexAlign +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------------ | ------------------------------------------------------------ | | Start | The child components are aligned with the start edge of the main axis. The first component is aligned with the main-start, and subsequent components are aligned with the previous one.| @@ -253,6 +303,8 @@ ## ItemAlign +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | ------------------------------------------------------------ | | Auto | The default configuration in the flex container is used. | @@ -264,6 +316,8 @@ ## FlexDirection +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------------- | ------------------------------ | | Row | The child components are arranged in the same direction as the main axis runs along the rows.| @@ -273,6 +327,8 @@ ## FlexWrap +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | ------------------------------------------------- | | NoWrap | The child components in the flex container are arranged in a single line, and they cannot overflow. | @@ -281,6 +337,8 @@ ## VerticalAlign +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------ | | Top | Top aligned. | @@ -289,6 +347,8 @@ ## ImageRepeat +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | -------------------------- | | X | The image is repeatedly drawn only along the horizontal axis.| @@ -298,6 +358,8 @@ ## ImageSize +Since API version 9, this API is supported in ArkTS widgets. + | Type | Description | | ------- | ------------------------------------------------------------ | | Cover | Default value. The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.| @@ -306,6 +368,8 @@ ## GradientDirection +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | ---------- | | Left | The gradient direction is from right to left.| @@ -320,6 +384,8 @@ ## SharedTransitionEffectType +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | ---------- | | Static | The element position remains unchanged on the target page, and transition opacity can be configured. Currently, this effect is only valid in redirecting to the target page.| @@ -327,6 +393,8 @@ ## FontStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ---------------- | | Normal | Standard font style.| @@ -334,6 +402,8 @@ ## FontWeight +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | -------------- | | Lighter | The font weight is lighter. | @@ -345,6 +415,8 @@ ## TextAlign +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | -------------- | | Start | Aligned with the start.| @@ -353,6 +425,8 @@ ## TextOverflow +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | -------------------------------------- | | Clip | Extra-long text is clipped. | @@ -361,6 +435,8 @@ ## TextDecorationType +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | ------------------ | | Underline | Line under the text. | @@ -370,6 +446,8 @@ ## TextCase +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | --------- | -------------------- | | Normal | The original case of the text is retained.| @@ -378,6 +456,8 @@ ## ResponseType8+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ---------- | -------------------------- | | LongPress | The menu is displayed when the component is long-pressed. | @@ -385,6 +465,8 @@ ## HoverEffect8+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | --------- | ---------------------------- | | Auto | Default hover effect.| @@ -394,6 +476,8 @@ ## Placement8+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------------- | ------------------------------------------------------------ | | Left | The popup is on the left of the component, vertically aligned with the component on the left. | @@ -411,6 +495,8 @@ ## CopyOptions9+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | -------------------- | | None | Copy is not allowed. | @@ -419,6 +505,8 @@ ## HitTestMode9+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ----------- | -------------------- | | Default | Both the node and its child node respond to the hit test of a touch event, but its sibling node is blocked from the hit test. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index c624d6b2c04cf07d34927f0e7c02ed9668136bbb..7a046d68f40f64d8dbb085c3c51d6451c3550290 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -16,6 +16,8 @@ Not supported Blank(min?: number | string) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -28,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -88,6 +90,6 @@ struct BlankExample { } } ``` -If the width of the parent container is not set, set **min** to specify the minimum width of the **\** component. +If the width of the parent container is not set, set **min** to specify the minimum width of the **\** component. ![blankmin](figures/blankmin.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md index c135dc560cff44bde103d3f7808705124938520d..75d67936b62bf0ac72456673ef1474e4840cb9fd 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -16,6 +16,8 @@ This component can contain only one child component. **API 1:** Button(options?: {type?: ButtonType, stateEffect?: boolean}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description | @@ -28,6 +30,8 @@ This component can contain only one child component. Creates a button component based on text content. In this case, the component cannot contain child components. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description | @@ -40,10 +44,13 @@ This component can contain only one child component. | Name | Type | Description | | ----------- | ----------- | --------------------------------- | -| type | ButtonType | Button type.
Default value: **ButtonType.Capsule** | -| stateEffect | boolean | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.
Default value: **true**| +| type | ButtonType | Button type.
Default value: **ButtonType.Capsule**
Since API version 9, this API is supported in ArkTS widgets.| +| stateEffect | boolean | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| ## ButtonType enums + +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------- | ------------------ | | Capsule | Capsule-type button (the round corner is half of the height by default).| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index 95fa03d4b2f7f94a02c450e37fca071a8db47d11..7bb73dc7db50b38fee5e68bd44a254291d27a8fc 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -14,6 +14,8 @@ Not supported Checkbox(options?: {name?: string, group?: string }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type| Mandatory | Description| @@ -28,16 +30,16 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type| Description| | ------------- | ------- | -------- | -| select | boolean | Whether the check box is selected.
Default value: **false**| -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the check box when it is selected.| +| select | boolean | Whether the check box is selected.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the check box when it is selected.
Since API version 9, this API is supported in ArkTS widgets.| ## Events In addition to the [universal events](ts-universal-events-click.md), the following attributes are supported. -| Name | Description| -| ----------| -------- | -|onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected. | +| Name | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets.| ## Example 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 64b116778047e73a49f79c4b4d859cab089fb6b4..0ff6c9dcf8bdf3c8e0cf55aaf3f68c439bdec48f 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 @@ -16,9 +16,9 @@ CheckboxGroup(options?: { group?: string }) Creates a check box group so that you can select or deselect all check boxes in the group at the same time. Check boxes and the check box group that share the group name belong to the same group. -**Parameters** - +Since API version 9, this API is supported in ArkTS widgets. +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -30,8 +30,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| selectAll | boolean | Whether to select all.
Default value: **false**
If **select** is explicitly set for check boxes in the group, the check box settings are prioritized.| -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.| +| selectAll | boolean | Whether to select all.
Default value: **false**
If **select** is explicitly set for check boxes in the group, the check box settings are prioritized.
Since API version 9, this API is supported in ArkTS widgets.| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -39,9 +39,12 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes due to a manual operation.| +| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes due to a manual operation.
Since API version 9, this API is supported in ArkTS widgets.| ## CheckboxGroupResult + +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | ------ | ------ | ------- | | name | Array<string> | Names of all the selected check boxes in the group.| @@ -49,6 +52,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ## SelectStatus +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description| | ----- | -------------------- | | All | All check boxes in the group are selected.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index a661b6abc36a1820fbcd634178d5cf2654911336..08d913698286ee0cb2cbfbc66386cd4a52a45bc9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -18,6 +18,8 @@ Not supported DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description| @@ -26,8 +28,10 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) | max | number | No | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.
- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion.
Default value: **100**| | type8+ | [DataPanelType](#datapaneltype) | No| Type of the data panel (dynamic modification is not supported).
Default value: **DataPanelType.Circle**| - ## DataPanelType + +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------| ------------ | | Line | Line data panel.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md index e49501637b426dddbc21258651ba5ae556544d3d..cee85008404560b115d9dc021ed98e59da47d36a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md @@ -16,16 +16,18 @@ Not supported Divider() +Since API version 9, this API is supported in ArkTS widgets. + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. | Name | Type | Description | | ----------- | ---------- | ------------------ | -| vertical | boolean | Whether a vertical divider is used. **false**: A horizontal divider is used.
**true**: A vertical divider is used.
Default value: **false**| -| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.| -| strokeWidth | number \| string | Width of the divider.
Default value: **1**| -| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the divider.
Default value: **LineCapStyle.Butt**| +| vertical | boolean | Whether a vertical divider is used. **false**: A horizontal divider is used.
**true**: A vertical divider is used.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | number \| string | Width of the divider.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| +| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the divider.
Default value: **LineCapStyle.Butt**
Since API version 9, this API is supported in ArkTS widgets.| ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md index e641340a69dad32e2db89c55ba2d44911d3258b7..3d55b17b5f9f7b2d8c9b742a1261d2902f4de04c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md @@ -42,7 +42,7 @@ Creates a **FormComponent** instance to display the provided widget. | Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ----------------------------------------------------------------------- | -| id | number | Yes | Widget ID. Set this parameter to **0** for a new widget. | +| id | number | Yes | Widget ID. Set this parameter to **0** for a new widget. | | name | string | Yes | Widget name. | | bundle | string | Yes | Bundle name of the widget. | | ability | string | Yes | Ability name of the widget. | @@ -63,7 +63,7 @@ Creates a **FormComponent** instance to display the provided widget. ## Attributes | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------- | -| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Yes | Size of the widget. | +| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Yes | Size of the widget. | | moduleName | string | Yes | Module name of the widget. | | dimension | [FormDimension](#formdimension) | No | Dimensions of the widget. The widgets in the 2 x 2, 4 x 4, and 4 x 2 dimensions are supported.
Default value: **Dimension_2_2**| | allowUpdate | boolean | No | Whether to allow the widget to update.
Default value: **true** | @@ -75,10 +75,10 @@ Creates a **FormComponent** instance to display the provided widget. | Name | Description | | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| onAcquired(callback: (info: { id: number }) => void) | Triggered when a widget is obtained. This API returns the ID of the obtained widget. | -| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | -| onRouter(callback: (info: any) => void) | Triggered when routing occurs for the widget. This API returns information in [routerEvent](../js-service-widget-ui/js-service-widget-syntax-hml.md#event-binding).| -| onUninstall(callback: (info: { id: number }) => void) | Triggered when a widget is uninstalled. This API returns the ID of the uninstalled widget. | +| onAcquired(callback: (info: { id: number }) => void) | Triggered when a widget is obtained. This API returns the ID of the obtained widget. | +| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | +| onRouter(callback: (info: any) => void) | Triggered when routing occurs for the widget. This API returns information in [routerEvent](../js-service-widget-ui/js-service-widget-syntax-hml.md#event-binding).| +| onUninstall(callback: (info: { id: number }) => void) | Triggered when a widget is uninstalled. This API returns the ID of the uninstalled widget. | ## Example @@ -108,7 +108,7 @@ struct CardExample { .visibility(Visibility.Visible) .onAcquired((form)=>{ console.log(`form info : ${JSON.stringify(form)}`); - this.fomId = form.id; + this.formId = form.id; }) .onError((err)=>{ console.log(`fail to add form, err: ${JSON.stringify(err)}`); diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index 5b4387a8c137fd14e9866238aef6785300f93918..2fe773177813164169dc35eddeba176a95fa4f89 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -17,6 +17,8 @@ Not supported Gauge(options:{value: number, min?: number, max?: number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -31,16 +33,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| value | number | Value of the chart. It can be dynamically changed.
Default value: **0**| -| startAngle | number | Start angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.
Default value: **0**| -| endAngle | number | End angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.
Default value: **360**| -| colors | Array<[ColorStop](#colorstop)> | Colors of the chart. Colors can be set for individual segments.| -| strokeWidth | Length | Stroke width of the chart.| +| value | number | Value of the chart. It can be dynamically changed.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| startAngle | number | Start angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| endAngle | number | End angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.
Default value: **360**
Since API version 9, this API is supported in ArkTS widgets.| +| colors | Array<[ColorStop](#colorstop)> | Colors of the chart. Colors can be set for individual segments.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | Stroke width of the chart.
Since API version 9, this API is supported in ArkTS widgets.| ## ColorStop Describes a gradient stop. +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | --------- | -------------------- | ------------------------------------------------------------ | | ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0, which means that the color is not displayed.| 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 e3fb8a003e68f5e54f3a48d4b9b8b15db5de3358..1562815bc640f37d2c83043be7d4c45bf0de2c8b 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 @@ -23,11 +23,13 @@ Image(src: string | PixelMap | Resource) Obtains an image from the specified source for subsequent rendering and display. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | 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.
\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.| +| 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.
\- Strings with the **datashare://** path prefix are supported, which are used to access the image path provided by a Data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
- ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes @@ -35,28 +37,30 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | -| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. | -| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover** | -| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
**NOTE**
This attribute is not applicable to SVG images.| -| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| -| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
**NOTE**
This attribute is not applicable to SVG images.| -| sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
**NOTE**
This attribute is not applicable to **PixelMap** objects.| -| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false** | -| fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false** | -| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.| -| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.
Default value: **true**| -| syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**| -| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.| -| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**| +| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported.
Since API version 9, this API is supported in ArkTS widgets.| +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover**
Since API version 9, this API is supported in ArkTS widgets.| +| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| +| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| +| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| +| sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to **PixelMap** objects or SVG images.| +| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.
Since API version 9, this API is supported in ArkTS widgets.| +| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| +| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.
This API is supported in ArkTS widgets.| +| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.| > **NOTE** > > To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**. -> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**. +> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**. ### ImageInterpolation +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------- | | None | Interpolation image data is not used. | @@ -66,6 +70,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ### ImageRenderMode +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | --------------------- | | Original | The image is rendered based on the original image, including the color. | @@ -77,9 +83,9 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status.
| -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.| -| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.| +| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status.
Since API version 9, this API is supported in ArkTS widgets.| +| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
Since API version 9, this API is supported in ArkTS widgets.| +| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -100,21 +106,21 @@ struct ImageExample1 { Text('default').fontSize(16).fontColor(0xcccccc).height(30) Row({ space: 5 }) { Image($r('app.media.ic_png')) - .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(110).border({ width: 1 }) .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.ic_gif')) - .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(110).border({ width: 1 }) .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.ic_svg')) - .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(110).border({ width: 1 }) .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } Row({ space: 5 }) { Image($r('app.media.img_example')) - .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(110).border({ width: 1 }) .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image(this.src) - .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(110).border({ width: 1 }) .overlay('network', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) }.margin({ top: 25, bottom: 10 }) } @@ -123,25 +129,25 @@ struct ImageExample1 { Text('objectFit').fontSize(16).fontColor(0xcccccc).height(30) Row({ space: 5 }) { Image($r('app.media.img_example')) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .objectFit(ImageFit.None).width(110).height(110) .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.img_example')) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .objectFit(ImageFit.Fill).width(110).height(110) .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.img_example')) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .objectFit(ImageFit.Cover).width(110).height(110) .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } Row({ space: 5 }) { Image($r('app.media.img_example_w250')) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .objectFit(ImageFit.Contain).width(110).height(110) .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.img_example_w250')) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .objectFit(ImageFit.ScaleDown).width(110).height(110) .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) }.margin({ top: 25 }) @@ -157,7 +163,7 @@ struct ImageExample1 { ### Loading Online Images -The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, use the [HTTP](../../connectivity/http-request.md) module in the SDK to send a network request, and then decode the returned data into a `PixelMap` in the **\** component. For details about image development, see [Image Development](../../media/image.md). The code snippet is as follows: +The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, use the [HTTP](../../connectivity/http-request.md) module in the SDK to send a network request, and then decode the returned data into a **PixelMap** in the **\** component. For details about image development, see [Image Development](../../media/image.md). The code snippet is as follows: ```tsx // @ts-nocheck @@ -234,18 +240,18 @@ struct ImageExample2 { Row({ space: 50 }) { Image($r('app.media.img_example')) .renderMode(ImageRenderMode.Original).width(100).height(100) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.img_example')) .renderMode(ImageRenderMode.Template).width(100).height(100) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30) Image('') .alt($r('app.media.Image_none')) - .width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(100).height(100).border({ width: 1 }) Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%') Row({ space: 50 }) { @@ -255,7 +261,7 @@ struct ImageExample2 { height: 150 }) .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .overlay('w:150 h:150', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.img_example')) .sourceSize({ @@ -263,22 +269,22 @@ struct ImageExample2 { height: 200 }) .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1) - .border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .border({ width: 1 }) .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30) Row({ space: 5 }) { Image($r('app.media.ic_health_heart')) - .width(120).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(120).height(125).border({ width: 1 }) .objectRepeat(ImageRepeat.XY).objectFit(ImageFit.ScaleDown) .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.ic_health_heart')) - .width(110).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(125).border({ width: 1 }) .objectRepeat(ImageRepeat.Y).objectFit(ImageFit.ScaleDown) .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) Image($r('app.media.ic_health_heart')) - .width(110).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed) + .width(110).height(125).border({ width: 1 }) .objectRepeat(ImageRepeat.X).objectFit(ImageFit.ScaleDown) .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } @@ -358,18 +364,14 @@ struct ImageExample3 { ```ts import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs'; -import context from '@ohos.app.ability.context'; +import context from '@ohos.app.ability.common'; @Entry @Component struct LoadImageExample { @State resourcesPath: string = '' @State sandboxPath: string = '' - context: context.AbilityContext - - aboutToAppear() { - this.context = getContext(this) as context.AbilityContext - } + context: context.UIAbility = getContext(this) as context.UIAbilityContext build() { Column() { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index 6a39e1c9f17f7a7150728509cdc5fdc32658189a..4381ad3257af51b69cb968af826f2359e3f30398 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -18,11 +18,13 @@ LoadingProgress() Creates a **\** component. +Since API version 9, this API is supported in ArkTS widgets. + ## Attributes | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\** component.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\** component.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index 9d905a65b1736315055c4b4582a5fa7cf5e8d00e..a6c0b032ca3d1234898704a15d87358800f737e7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -17,29 +17,31 @@ Not supported Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | start | boolean | Yes| Whether to start scrolling.| | step | number | No| Scrolling step.
Default value: **6**, in vp| -| loop | number | No| Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.
Default value: **-1**| +| loop | number | No| Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.
Default value: **-1**
**NOTE**
Regardless of the value, the marquee scrolls only once on an ArkTS widget.| | fromStart | boolean | No| Whether the text scrolls from the start.
Default value: **true**| | src | string | Yes| Text to scroll.| ## Attributes -| Name | Type| Description | -| ---------- | -------- | ------------------------------------ | -| allowScale | boolean | Whether to allow text to scale.
Default value: **false**| +| Name | Type| Description | +| ---------- | -------- | ------------------------------------------------------------ | +| allowScale | boolean | Whether to allow text to scale.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| ## Events | Name| Description| | -------- | -------- | -| onStart(event: () => void) | Triggered when the marquee starts scrolling.| -| onBounce(event: () => void) | Triggered when the marquee has reached the end. This event will be triggered for multiple times if the **loop** attribute is not set to **1**.| -| onFinish(event: () => void) | Triggered when the marquee has finished the number of scrolling times set by the **loop** attribute.| +| onStart(event: () => void) | Triggered when the marquee starts scrolling.
Since API version 9, this API is supported in ArkTS widgets.| +| onBounce(event: () => void) | Triggered when the marquee has reached the end. This event will be triggered for multiple times if the **loop** attribute is not set to **1**.
Since API version 9, this API is supported in ArkTS widgets.| +| onFinish(event: () => void) | Triggered when the marquee has finished the number of scrolling times set by the **loop** attribute.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md new file mode 100644 index 0000000000000000000000000000000000000000..65f7d17c6cc5f494896482669b720539aa07ad41 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md @@ -0,0 +1,95 @@ +# Menu + +The **\** component is a vertical list of items presented to the user. + +> **NOTE** +> +> This component is supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Child Components + +This component contains the [MenuItem](ts-basic-components-menuitem.md) and [MenuItemGroup](ts-basic-components-menuitemgroup.md) child components. + +## APIs + +Menu() + +Creates a fixed container for a menu. This API does not have any parameters. + +## Attributes + +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + +| Name | Type | Description | +| -------- | ------------------------- | ---------------------------------------------------------------- | +| fontSize | [Length](ts-types.md#length) | Font size that applies to all texts in the menu. When **Length** is of the number type, the unit is fp.| + +## Example + +```ts +@Entry +@Component +struct Index { + @State select: boolean = true + private iconStr: ResourceStr = $r("app.media.view_list_filled") + private iconStr2: ResourceStr = $r("app.media.view_list_filled") + + @Builder + SubMenu() { + Menu() { + MenuItem({ content: "Copy", labelInfo: "Ctrl+C" }) + MenuItem({ content: "Paste", labelInfo: "Ctrl+V" }) + } + } + + @Builder + MyMenu(){ + Menu() { + MenuItem({ startIcon: $r("app.media.icon"), content: "Menu option" }) + MenuItem({ startIcon: $r("app.media.icon"), content: "Menu option" }) + .enabled(false) + MenuItem({ + startIcon: this.iconStr, + content: "Menu option", + endIcon: $r("app.media.arrow_right_filled"), + builder: this.SubMenu.bind(this) + }) + MenuItemGroup({ header: 'Subtitle' }) { + MenuItem ({ content: "Menu option" }) + .selectIcon(true) + .selected(this.select) + .onChange((selected) => { + console.info("menuItem select" + selected); + this.iconStr2 = $r("app.media.icon"); + }) + MenuItem({ + startIcon: $r("app.media.view_list_filled"), + content: "Menu option", + endIcon: $r("app.media.arrow_right_filled"), + builder: this.SubMenu.bind(this) + }) + } + MenuItem({ + startIcon: this.iconStr2, + content: "Menu option", + endIcon: $r("app.media.arrow_right_filled") + }) + } + } + + build() { + Row() { + Column() { + Text('click to show menu') + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .bindMenu(this.MyMenu) + .width('100%') + } + .height('100%') + } +} +``` + +![menu1](figures/menu1.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md new file mode 100644 index 0000000000000000000000000000000000000000..cce67b34b9d5c4b50f1ac55dcfffcc2fda09e3ee --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md @@ -0,0 +1,50 @@ +# MenuItem + +The **\** component represents an item in a menu. + +> **NOTE** +> +> This component is supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Child Components + +Not supported + +## APIs + +MenuItem(value?: MenuItemOptions| CustomBuilder) + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | ----------------------------------------------------------------------------------------------------------------------------- | ---- | ---------------------------- | +| value | [MenuItemOptions](ts-basic-components-menuitem.md#menuitemoptions) \| [CustomBuilder](ts-types.md#custombuilder8) | No | Information about the menu item.| + +## MenuItemOptions + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------- | ---- | -------------------------------------- | +| startIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the left of the menu item. | +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the menu item. | +| endIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the right of the menu item. | +| labelInfo | [ResourceStr](ts-types.md#resourcestr) | No | Information about the ending label, for example, shortcut **Ctrl+C**. | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Builder for a level-2 menu. | + +## Attributes + +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + +| Name | Type| Description | +| ---------- | -------- | ---------------------------------------- | +| selected | boolean | Whether the menu item is selected.
Default value: **false** | +| selectIcon | boolean | Whether to display the icon of the menu item being selected.| + +## Events + +| Name | Type | Description | +| -------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| onChange | (selected: boolean) => void | Triggered when the selection status of the menu item is changed manually.
The value **true** means that the menu item is selected, and **false** means the opposite. | + +## Example + +For details, see [Example in Menu](ts-basic-components-menu.md#example). diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menuitemgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitemgroup.md new file mode 100644 index 0000000000000000000000000000000000000000..1c1b19c668d4a95ef6ab10bb2d5549b643374e40 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitemgroup.md @@ -0,0 +1,32 @@ +# MenuItemGroup + +The **\** component represents a group of menu items. + +> **NOTE** +> +> This component is supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Child Components + +This component contains the [MenuItem](ts-basic-components-menuitem.md) child component. + +## APIs + +MenuItemGroup(value?: MenuItemGroupOptions) + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | -------------------------------------------------------------------------------------- | ---- | ------------------------------------------- | +| value | [MenuItemGroupOptions](ts-basic-components-menuitemgroup.md#menuitemgroupoptions) | No | Header and footer of the menu item group.| + +## MenuItemGroupOptions + +| Name | Type | Mandatory| Description | +| ------ | ----------------------------------------------------------------------------------------- | ---- | ----------------------------- | +| header | [ResourceStr](ts-types.md#resourcestr) \| [CustomBuilder](ts-types.md#custombuilder8) | No | Header of the menu item group.| +| footer | [ResourceStr](ts-types.md#resourcestr) \| [CustomBuilder](ts-types.md#custombuilder8) | No | Footer of the menu item group.| + +## Sample + +For details, see [Example in Menu](ts-basic-components-menu.md#example). diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md index cee680621ce514b190bbddd8248647bbef0394bc..041045dc6986adfcc82696f3df7d314aaabccbe7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md @@ -1,14 +1,11 @@ # PluginComponent -The **\** allows the UI provided by an external application to be displayed in the application. +The **\** allows the UI provided by an external application to be displayed in the application. To implement the update through inter-process communication (IPC), see [@ohos.pluginComponent](../apis/js-apis-plugincomponent.md). > **NOTE** > > - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. -> -> - The APIs provided by this component are system APIs. - ## Child Components @@ -23,166 +20,41 @@ Creates a **PluginComponent** to display the UI provided by an external applicat **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | {
template: PluginComponentTemplate,
data: KVObject
} | Yes | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.
**data**: data passed to the **PluginComponent** provider.| +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------------- | +| value | {
template: [PluginComponentTemplate](#plugincomponenttemplate),
data: [KVObject](../apis/js-apis-plugincomponent.md#kvobject)
} | Yes | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.
**data**: data passed to the **PluginComponent** provider.| ## PluginComponentTemplate -| Name | Type | Description | -| ------- | ------ | ----------------------- | -| source | string | Component template name. | -| ability | string | Name of the provider ability.| +| Name | Type | Description | +| ---------- | ------ | --------------------------- | +| source | string | Component template name. | +| bundleName | string | Bundle name of the provider ability.| ## Events -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onComplete(callback: () => void) | Triggered when the component loading is complete. | +| Name | Description | +| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| onComplete(callback: () => void) | Triggered when the component loading is complete. | | onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information.| - -## PluginComponentManager - -Provides APIs for the **PluginComponent**. You can use these APIs to request components and data and send component templates and data. - - -## Modules to Import - - -``` -import pluginComponentManager from '@ohos.plugincomponent' -``` - - -## push - -push(param: PushParameters, callback: AsyncCallback<void>): void - -Pushes the component and data to the component user. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------------------------- | -| param | PushParameters | Yes | Information about the component user. For details, see **PushParameters**.| -| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result. | - -**PushParameters** - -| Name | Type | Mandatory | Description | -| --------- | -------- | ---- | --------------- | -| want | Want | Yes | Ability information of the component user.| -| name | string | Yes | Component name. | -| data | KVObject | No | Component data value. | -| extraData | KVObject | No | Additional data value. | -| jsonPath | string | No | Path of the **external.json** file that stores template paths. | - -**Example** - -For details, see [PluginComponent Provider](#plugincomponent-provider). - - -## request - -request(param: RequestParameters, callback: AsyncCallback<RequestCallbackParameters>): void - -Requests the component from the component provider. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| param | RequestParameters | Yes | Information about the component request. For details, see **RequestParameters**.| -| callback | AsyncCallback**"push"**: The component provider pushes data to the component user.
**"request"**: The component user proactively requests data from the component provider.| -| callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see **callback**. | - -**callback** - -| Name | Type | Description | -| ---------------------- | ---------------------------------------- | ---------------------------------------- | -| OnRequestEventCallback | (source: Want,
name: string,
data: KVObject ) =>RequestEventResult | Callback for the data request event.
**source**: ability information of the component requester.
**name**: name of the requested component.
**data**: additional data.
Return value: request data and result.| -| OnPushEventCallback | (source: Want,
template: PluginComponentTemplate,
data: KVObject,
extraData: KVObject
) => void | Callback used to receive the data pushed by the component provider.
**source**: ability information of the component provider.
**template**: component template.
**data**: component update data.
**extraData**: additional data.| - -**RequestEventResult** - -| Name | Type | Description | -| --------- | -------- | ---------- | -| template | string | Component name.| -| data | KVObject | Component data.| -| extraData | KVObject | Additional data.| - -**Example** - -For details, see [PluginComponent Tools](#plugincomponent-tools). - -**KVObject** - -| Name | Type | Description | -| ---- | ---------------------------------------- | ---------------------------------------- | -| key | number \| string \| boolean \| Array \| KVObject | Key of the **KVObject**. **KVObject** uses **key** and **value** to store data. If **key** is of the string type, **value** can be of the number, string, boolean, array type or another **KVObject**.| - - -**Description of the external.json file** - -The **external.json** file is created by developers. This file stores component names and template paths in key-value pairs. The component name is the key, and the corresponding template path is the value. - -**Example** - -For details, see [external.json](#externaljson). - ## Example ### PluginComponent User - ```ts //PluginUserExample.ets -import plugin from "plugin_component.js" +import plugin from "./plugin_component.js" @Entry @Component struct PluginUserExample { @StorageLink("plugincount") plugincount: Object[] = [ - { source: 'plugincomponent1', ability: 'com.example.plugin' }, - { source: 'plugintemplate', ability: 'com.example.myapplication' }, - { source: 'plugintemplate', ability: 'com.example.myapplication' }] + { source: 'plugincomponent1', bundleName: 'com.example.plugin' }, + { source: 'plugintemplate', bundleName: 'com.example.myapplication' }, + { source: 'plugintemplate', bundleName: 'com.example.myapplication' }] build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -209,7 +81,7 @@ struct PluginUserExample { }) ForEach(this.plugincount, item => { PluginComponent({ - template: { source: 'plugincomponent1', ability: 'com.example.plugin' }, + template: { source: 'PluginProviderExample', bundleName: 'com.example.plugin' }, data: { 'countDownStartValue': 'new countDownStartValue' } }).size({ width: 500, height: 100 }) .onComplete(() => { @@ -230,7 +102,7 @@ struct PluginUserExample { ```ts //PluginProviderExample.ets -import plugin from "plugin_component.js" +import plugin from "./plugin_component.js" @Entry @Component @@ -270,7 +142,7 @@ struct PluginProviderExample { ### PluginComponent Tools - +#### FA Model ```js //plugin_component.js import pluginComponentManager from '@ohos.pluginComponent' @@ -308,10 +180,10 @@ export default { pluginComponentManager.push( { want: { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.plugin", + abilityName: "com.example.myapplication.PluginProviderExample", }, - name: "plugintemplate", + name: "PluginProviderExample", data: { "key_1": "plugin component test", "key_2": 34234 @@ -330,10 +202,10 @@ export default { // The component user proactively sends data. pluginComponentManager.request({ want: { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.plugin", + abilityName: "com.example.myapplication.PluginProviderExample", }, - name: "plugintemplate", + name: "PluginProviderExample", data: { "key_1": "plugin component test", "key_2": 34234 @@ -358,10 +230,98 @@ export default { } ``` +#### Stage Model +```js +//plugin_component.js +import pluginComponentManager from '@ohos.pluginComponent' + +function onPushListener(source, template, data, extraData) { + console.log("onPushListener template.source=" + template.source) + var jsonObject = JSON.parse(data.componentTemplate.source) + console.log("request_callback1:source json object" + jsonObject) + var jsonArry = jsonObject.ExternalComponent + for (var i in jsonArry) { + console.log(jsonArry[i]) + } + console.log("onPushListener:source json object" + jsonObject) + console.log("onPushListener:source json string" + JSON.stringify(jsonObject)) + console.log("onPushListener template.ability=" + template.ability) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) +} -### external.json -```json +function onRequestListener(source, name, data) { - "plugintemplate": "ets/pages/plugintemplate.js", - "plugintemplate2": "ets/pages/plugintemplate2.js" + console.log("onRequestListener name=" + name); + console.log("onRequestListener data=" + JSON.stringify(data)); + return {template:"plugintemplate", data:data}; } + +export default { + //register listener + onListener() { + pluginComponentManager.on("push", onPushListener) + pluginComponentManager.on("request", onRequestListener) + }, + Push() { + // The component provider proactively sends data. + pluginComponentManager.push( + { + owner: { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + }, + target: { + bundleName: "com.example.plugin", + abilityName: "com.example.myapplication.PluginProviderExample", + }, + name: "PluginProviderExample", + data: { + "key_1": "plugin component test", + "key_2": 34234 + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", + }, + (err, data) => { + console.log("push_callback: push ok!"); + } + ) + }, + Request() { + // The component user proactively sends data. + pluginComponentManager.request({ + owner: { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + }, + target: { + bundleName: "com.example.plugin", + abilityName: "com.example.myapplication.PluginProviderExample", + }, + name: "PluginProviderExample", + data: { + "key_1": "plugin component test", + "key_2": 34234 + }, + jsonPath: "", + }, + (err, data) => { + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + var jsonObject = JSON.parse(data.componentTemplate.source) + console.log("request_callback:source json object" + jsonObject) + var jsonArry = jsonObject.ExternalComponent + for (var i in jsonArry) { + console.log(jsonArry[i]) + } + console.log("request_callback:source json string" + JSON.stringify(jsonObject)) + console.log("request_callback: data=" + JSON.stringify(data.data)) + console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) + } + ) + } +} +``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 98d9d6e2b1a2d0839071d2f72689d2cae6cb15ea..695d7f0cdff2c7381818f975e9eb31bf18a1d881 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -18,17 +18,21 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) Creates a progress indicator. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.| -| total | number | No| Total progress.
Default value: **100**| -| type8+ | [ProgressType](#progresstype) | No| Style the progress indicator.
Default value: **ProgressType.Linear**| +| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| +| total | number | No| Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| +| type8+ | [ProgressType](#progresstype) | No| Style the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| | styledeprecated | [ProgressStyle](#progressstyle) | No| Type of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| ## ProgressType +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------- | -------- | | Linear | Linear type. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width.| @@ -39,6 +43,8 @@ Creates a progress indicator. ## ProgressStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | --------- | ------------------------------------------------------------ | | Linear | Linear type.| @@ -51,10 +57,10 @@ Creates a progress indicator. | Name| Type| Description| | -------- | -------- | -------- | -| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.| -| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.| -| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | Component style.
- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.
Default value: **4.0Vp**
- **scaleCount**: number of divisions on the determinate ring-type process indicator.
Default value: **120**
- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**| +| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.
Since API version 9, this API is supported in ArkTS widgets.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Since API version 9, this API is supported in ArkTS widgets.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Since API version 9, this API is supported in ArkTS widgets.| +| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | Component style.
- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.
Default value: **4.0Vp**
- **scaleCount**: number of divisions on the determinate ring-type process indicator.
Default value: **120**
- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index 804d82a8d3b1dcfa91a87384b9f3905acdd39cce..e5dfa9aa5304d58c76fdfe87aaf7ade4623db417 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -16,6 +16,8 @@ Not supported QRCode(value: string) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -28,8 +30,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the QR code.
Default value: **Color.Black**| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the QR code.
Default value: **Color.White**| +| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the QR code.
Default value: **Color.Black**
Since API version 9, this API is supported in ArkTS widgets.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the QR code.
Default value: **Color.White**
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -45,17 +47,21 @@ Among all the universal events, only the [click event](ts-universal-events-click @Component struct QRCodeExample { private value: string = 'hello world' - build() { Column({ space: 5 }) { - Text('normal').fontSize(9).width('90%').fontColor(0xCCCCCC) + Text('normal').fontSize(9).width('90%').fontColor(0xCCCCCC).fontSize(30) QRCode(this.value).width(200).height(200) - Text('color').fontSize(9).width('90%').fontColor(0xCCCCCC) + // Set the color for the QR code. + Text('color').fontSize(9).width('90%').fontColor(0xCCCCCC).fontSize(30) QRCode(this.value).color(0xF7CE00).width(200).height(200) + + // Set the background color for the QR code. + Text('backgroundColor').fontSize(9).width('90%').fontColor(0xCCCCCC).fontSize(30) + QRCode(this.value).width(200).height(200).backgroundColor(Color.Orange) }.width('100%').margin({ top: 5 }) } } ``` -![en-us_image_0000001256858415](figures/en-us_image_0000001256858415.png) +![qrcode](figures/qrcode.png) 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 f000af680f63404ce37e365b777fbe9e03b96b5d..94bdbe86681322c5f0b0e4dedf31d6e037447d5b 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 @@ -16,6 +16,8 @@ Not supported Radio(options: {value: string, group: string}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -29,7 +31,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| checked | boolean | Whether the radio button is selected.
Default value: **false**| +| checked | boolean | Whether the radio button is selected.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -37,7 +39,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onChange(callback: (isChecked: boolean) => void) | Triggered when the selected state of the radio button changes.
- If **isChecked** is **true**, the radio button is selected.
- If **isChecked** is **false**, the radio button is not selected.| +| onChange(callback: (isChecked: boolean) => void) | Triggered when the selected state of the radio button changes.
- If **isChecked** is **true**, the radio button is selected.
- If **isChecked** is **false**, the radio button is not selected.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md index 560a20be960ff723ccd1a633272df3cb58024e54..d78f3a705501daf305b4d3ee01a33a57c568a6a0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -16,6 +16,8 @@ Not supported Rating(options?: { rating: number, indicator?: boolean }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -28,16 +30,16 @@ Rating(options?: { rating: number, indicator?: boolean }) | Name| Type| Description| | -------- | -------- | -------- | -| stars | number | Total number of stars.
Default value: **5**| -| stepSize | number | Step of an operation.
Default value: **0.5**| -| starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | **backgroundUri**: image link of the unselected star. You can use the default image or a custom local image.
**foregroundUri**: image path of the selected star. You can use the default image or a custom local image.
**secondaryUir**: image path of the partially selected star. You can use the default image or a custom local image.| +| stars | number | Total number of stars.
Default value: **5**
Since API version 9, this API is supported in ArkTS widgets.| +| stepSize | number | Step of an operation.
Default value: **0.5**
Since API version 9, this API is supported in ArkTS widgets.| +| starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | **backgroundUri**: image link of the unselected star. You can use the default image or a custom local image.
**foregroundUri**: image path of the selected star. You can use the default image or a custom local image.
**secondaryUir**: image path of the partially selected star. You can use the default image or a custom local image.
Since API version 9, this API is supported in ArkTS widgets.| ## Events | Name| Description| | -------- | -------- | -| onChange(callback:(value: number) => void) | Triggered when the rating value changes.| +| onChange(callback:(value: number) => void) | Triggered when the rating value changes.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 39321308ca3063bc5da81e5ec94d353b02684cd1..fb316a779bf73f0efcb6c7208960b7a6b10c871c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -31,6 +31,10 @@ RichText(content:string) | onStart(callback: () => void) | Triggered when web page loading starts. | | onComplete(callback: () => void) | Triggered when web page loading is completed.| +## Attributes + +Among the [universal attributes](ts-universal-attributes-size.md), only the **width**, **height**, **size**, and **layoutWeight** attributes are supported. + ## Supported Tags | Name| Description| Example| @@ -39,13 +43,13 @@ RichText(content:string) | \

\

| Defines a paragraph.| \

This is a paragraph\

| | \
| Inserts a newline character.| \

This is a paragraph\
This is a new paragraph\

| | \ | Defines the font style for the text contained within it, including the font face, size, and color.| \This is in red\ | -| \
| Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \

This is a paragraph\

\
\

This is a paragraph\

| +| \
| Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \

This is text\

\
\

This is text\

| | \\ | Defines an image.| \\ | | \
\
| Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \
\

This is the heading in a div element\

\
| | \\ | Displays text in italic style.| \This is in italic style\| | \\ | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \ tag where it could be confused with a hyperlink.| \

\This is an underlined paragraph\\

| | \ | Used to embed CSS within an HTML document.| \ | -| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is a paragraph\

| +| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is text\

| | \ | Embeds or references a client-side script, such as JavaScript.| \ | ## Example @@ -66,7 +70,7 @@ struct RichTextExample { '
' + '

Font size: 35px; line height: 45px

' + '

' + - '

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

'; + '

This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text.

'; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, @@ -78,6 +82,29 @@ struct RichTextExample { .onComplete(() => { console.info('RichText onComplete'); }) + .width(500) + .height(400) + .backgroundColor(0XBDDB69) + RichText('layoutWeight(1)') + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) + .size({ width: '100%', height: 110 }) + .backgroundColor(0X92D6CC) + .layoutWeight(1) + RichText('layoutWeight(2)') + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) + .size({ width: '100%', height: 110 }) + .backgroundColor(0X92C48D) + .layoutWeight(2) } } } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index b8bf88b154875799dbaa04ace76d8ea12fcc5d03..bea534a1a1861e1ad2183d0ed1455127f762c65c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -16,6 +16,8 @@ Not supported Slider(options?: {value?: number, min?: number, max?: number, step?: number, style?: SliderStyle, direction?: Axis, reverse?: boolean}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -30,6 +32,8 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty ## SliderStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------- | -------- | | OutSet | The slider is on the slider track.| @@ -42,12 +46,12 @@ Except touch target attributes, the universal attributes are supported. | Name| Type| Description| | -------- | -------- | -------- | -| blockColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider.| -| trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.| -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.| -| showSteps | boolean | Whether to display the current step.
Default value: **false**| -| showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.
Default value: **false**| -| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.| +| blockColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider.
Since API version 9, this API is supported in ArkTS widgets.| +| trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.
Since API version 9, this API is supported in ArkTS widgets.| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.
Since API version 9, this API is supported in ArkTS widgets.| +| showSteps | boolean | Whether to display the current step.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -56,10 +60,12 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow | Name| Description| | -------- | -------- | -| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Invoked when the slider slides.
**value**: current slider value. If the return value contains decimals, you can use **Math.toFixed()** to process the data to the desired precision.
**mode**: dragging state.| +| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Invoked when the slider slides.
**value**: current slider value. If the return value contains decimals, you can use **Math.toFixed()** to process the data to the desired precision.
**mode**: dragging state.
Since API version 9, this API is supported in ArkTS widgets.| ## SliderChangeMode +Since API version 9, this API is supported in ArkTS widgets. + | Name| Value| Description| | -------- | -------- | -------- | | Begin | 0 | The user starts to drag the slider.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md index 0c7c4044634d3751fb653df18bb1be10d98dccaa..f8d1fec7469a7b9b16757fcb59522c1f60d20710 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -16,6 +16,8 @@ Not supported Span(value: string | Resource) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -23,21 +25,20 @@ Span(value: string | Resource) | value | string \| [Resource](ts-types.md#resource) | Yes| Plain text.| - ## Attributes In addition to the [universal text style](ts-universal-attributes-text-style.md) attributes, the following attributes are supported. | Name| Type| Description| | -------- | -------- | -------- | -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None
color: Color.Black
} | -| letterSpacing | number \| string | Letter spacing. | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| +| letterSpacing | number \| string | Letter spacing. A negative value tightens the spacing; a positive value loosens the spacing, and the letters are spread farther apart with the value.
Since API version 9, this API is supported in ArkTS widgets. | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| ## Events -Among all the [universal events](ts-universal-attributes-click.md), only the click event is supported. +Among all the universal events, only the [click event](ts-universal-attributes-click.md) is supported. > **NOTE** > @@ -59,29 +60,59 @@ struct SpanExample { .decoration({ type: TextDecorationType.None, color: Color.Red }) } + // Add a line under the text. Text('Text Decoration').fontSize(9).fontColor(0xCCCCCC) Text() { Span('I am Underline-span').decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(12) } + Text() { - Span('I am LineThrough-span').decoration({ type: TextDecorationType.LineThrough, color: Color.Red }).fontSize(12) + Span('I am LineThrough-span') + .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }) + .fontSize(12) } + Text() { Span('I am Overline-span').decoration({ type: TextDecorationType.Overline, color: Color.Red }).fontSize(12) } + // Set the letter spacing. + Text('LetterSpacing').fontSize(9).fontColor(0xCCCCCC) + Text() { + Span('span letter spacing') + .letterSpacing(0) + .fontSize(12) + } + + Text() { + Span('span letter spacing') + .letterSpacing(-2) + .fontSize(12) + } + + Text() { + Span('span letter spacing') + .letterSpacing(3) + .fontSize(12) + } + + + // Set the text case. Text('Text Case').fontSize(9).fontColor(0xCCCCCC) Text() { - Span('I am Lower-span').textCase(TextCase.LowerCase).fontSize(12) - .decoration({ type: TextDecorationType.None, color: Color.Red }) + Span('I am Lower-span').fontSize(12) + .textCase(TextCase.LowerCase) + .decoration({ type: TextDecorationType.None }) } + Text() { - Span('I am Upper-span').textCase(TextCase.UpperCase).fontSize(12) - .decoration({ type: TextDecorationType.None, color: Color.Red }) + Span('I am Upper-span').fontSize(12) + .textCase(TextCase.UpperCase) + .decoration({ type: TextDecorationType.None }) } }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 }) } } ``` -![en-us_image_0000001257138363](figures/en-us_image_0000001257138363.gif) +![span](figures/span.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 67eedfeb76158d1cd94e57196811406d46dcbf3b..9f2fdd7b839eaa85f8900968ce42a7e7d5304a40 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -16,6 +16,8 @@ This component can contain the [\](ts-basic-components-span.md) child comp Text(content?: string | Resource) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -28,17 +30,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | ----------------------- | ----------------------------------- | ------------------------------------------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set the vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute.| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect. | -| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed. | -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
} | -| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**. | -| letterSpacing | number \| string | Letter spacing. | -| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxline**, or a layout size constraint. | -| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxline**, or a layout size constraint. | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set the vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute.
Since API version 9, this API is supported in ArkTS widgets.| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.
Since API version 9, this API is supported in ArkTS widgets.| +| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.
Since API version 9, this API is supported in ArkTS widgets.| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| +| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**.
Since API version 9, this API is supported in ArkTS widgets. | +| letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets. | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxline**, or a layout size constraint.
Since API version 9, this API is supported in ArkTS widgets. | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxline**, or a layout size constraint.
Since API version 9, this API is supported in ArkTS widgets. | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index bc16a8dd1638b0ad7e1538891707422c60d7ad2b..e4b6ba1ad47c9e06f3f26e6b47f4afd505b6aa36 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index b7a72430211190079eec4d628a61658bb664bc21..3769a949422ac922318ad203fb2a7bebd676e44c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -38,7 +38,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | maxLength | number | Maximum number of characters in the text input. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| | showPasswordIcon9+ | boolean | Whether to display the show password icon at the end of the password text box.
Default value: **true**| | style9+ | [TextInputStyle](#textinputstyle9) | Text input style.
Default value: **TextInputStyle.Default**| | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.
Default value: **TextAlign.Start** | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index f1f8e0b31d765b58e10b43d23f19ffdab04bac1d..7c3994074a9bf4124800346196515150f020ffc6 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -6,6 +6,10 @@ The **\** component provides a clickable element in the check box, butto > > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + + + + ## Child Components This component can contain child components only when **ToggleType** is set to **Button**. @@ -15,6 +19,8 @@ This component can contain child components only when **ToggleType** is set to * Toggle(options: { type: ToggleType, isOn?: boolean }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory | Description | @@ -24,6 +30,9 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) ## ToggleType + +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | -------- | ---------------- | | Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 14 vp,
right: 6 vp,
bottom: 14 vp,
left: 6 vp
} | @@ -35,15 +44,15 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) | Name | Parameter | Description | | ---------------- | --------------------------- | ---------------------- | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component when it is turned on.| -| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.
**NOTE**
This attribute is valid only when **type** is set to **ToggleType.Switch**. | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component when it is turned on.
Since API version 9, this API is supported in ArkTS widgets.| +| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.
**NOTE**
This attribute is valid only when **type** is set to **ToggleType.Switch**.
Since API version 9, this API is supported in ArkTS widgets.| ## Events | Name| Description| | -------- | -------- | -| onChange(callback: (isOn: boolean) => void) | Triggered when the toggle status changes.| +| onChange(callback: (isOn: boolean) => void) | Triggered when the toggle status changes.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index b49036458e4332cc8444996783545d0760ac8bd8..850480bf54c95ad30e6b58fa05156b9ab9c01771 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -1,6 +1,6 @@ # Web -The **** component can be used to display web pages. +The **** component can be used to display web pages. It can be used with the [@ohos.web.webview](../apis/js-apis-webview.md) module, which provides APIs for web control. > **NOTE** > @@ -16,29 +16,32 @@ Not supported ## APIs -Web(options: { src: ResourceStr, controller: WebController | WebviewController}) +Web(options: { src: ResourceStr, controller: WebviewController | WebController}) > **NOTE** > > Transition animation is not supported. -> Different **\** components on the same page must be bound to different **WebController**s. +> +> **\** components on a page must be bound to different **WebviewController**s. **Parameters** | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ------- | -| src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource.| -| controller | [WebController](#webcontroller) \| [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller) | Yes | Controller. | +| src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource. To access local resource files, use the **$rawfile** or **resource** protocol. To load a local resource file in the sandbox outside of the application package, use **file://** to specify the path of the sandbox.| +| controller | [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller) \| [WebController](#webcontroller) | Yes | Controller. **WebController** is deprecated since API version 9. You are advised to use **WebviewController** instead.| **Example** Example of loading online web pages: ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -46,6 +49,8 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) } } ``` + + Example of loading local web pages: ```ts // xxx.ets import web_webview from '@ohos.web.webview' @@ -56,36 +61,77 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + // Load a local resource file through $rawfile. + Web({ src: $rawfile("index.html"), controller: this.controller }) } } } ``` - Example of loading local web pages: ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: $rawfile("index.html"), controller: this.controller }) + // Load a local resource file through the resource protocol. + Web({ src: "resource://rawfile/index.html", controller: this.controller }) } } } ``` - ```html - - - - -

Hello World

- - - ``` + Example of loading local resource files in the sandbox: + + 1. Use[globalthis](../../application-models/uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) to obtain the path of the sandbox. + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + let url = 'file://' + globalThis.filesDir + '/xxx.html' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + // Load the files in the sandbox. + Web({ src: url, controller: this.controller }) + } + } + } + ``` + + 2. Modify the **MainAbility.ts** file. + + The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining the Application Development Path](../../application-models/application-context-stage.md#obtaining-the-application-development-path). + ```ts + // xxx.ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import web_webview from '@ohos.web.webview'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Bind filesDir to the globalThis object to implement data synchronization between the UIAbility component and the UI. + globalThis.filesDir = this.context.filesDir + console.log("Sandbox path is " + globalThis.filesDir) + } + } + ``` + + ```html + + + + +

Hello World

+ + + ``` ## Attributes @@ -107,10 +153,12 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -136,10 +184,12 @@ Sets whether to enable access to the file system in the application. This settin ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -164,10 +214,12 @@ Sets whether to enable automatic image loading. By default, this feature is enab **Example** ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -180,7 +232,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab ### javaScriptProxy javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\, - controller: WebController | WebviewController}) + controller: WebviewController | WebController}) Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. The parameters cannot be updated. @@ -191,41 +243,10 @@ Registers a JavaScript object with the window. APIs of this object can then be i | object | object | Yes | - | Object to be registered. Methods can be declared, but attributes cannot. | | name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.| | methodList | Array\ | Yes | - | Methods of the JavaScript object to be registered at the application side. | -| controller | [WebController](#webcontroller) or [WebviewController](../apis/js-apis-webview.md#webviewcontroller) | Yes | - | Controller. | +| controller | [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller) \| [WebController](#webcontroller) | Yes | - | Controller. **WebController** is deprecated since API version 9. You are advised to use **WebviewController** instead.| **Example** - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - testObj = { - test: (data1, data2, data3) => { - console.log("data1:" + data1) - console.log("data2:" + data2) - console.log("data3:" + data3) - return "AceString" - }, - toString: () => { - console.log('toString' + "interface instead.") - } - } - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - .javaScriptAccess(true) - .javaScriptProxy({ - object: this.testObj, - name: "objName", - methodList: ["test", "toString"], - controller: this.controller, - }) - } - } - } - ``` ```ts // xxx.ets import web_webview from '@ohos.web.webview' @@ -276,10 +297,12 @@ Sets whether JavaScript scripts can be executed. By default, JavaScript scripts ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -305,10 +328,12 @@ Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. B ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State mode: MixedMode = MixedMode.All build() { Column() { @@ -335,10 +360,12 @@ Sets whether to enable access to online images through HTTP and HTTPS. By defaul ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -364,10 +391,12 @@ Sets whether to enable zoom gestures. By default, this feature is enabled. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -393,10 +422,12 @@ Sets whether to load web pages by using the overview mode. By default, this feat ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -422,10 +453,12 @@ Sets whether to enable database access. By default, this feature is disabled. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -451,10 +484,12 @@ Sets whether to enable geolocation access. By default, this feature is enabled. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -480,10 +515,12 @@ Sets whether video playback must be started by user gestures. This API is not ap ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State access: boolean = true build() { Column() { @@ -510,10 +547,12 @@ Sets whether to enable the multi-window permission. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -539,10 +578,12 @@ Sets whether to display the horizontal scrollbar, including the default system s ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -590,10 +631,12 @@ Sets whether to display the vertical scrollbar, including the default system scr ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -642,10 +685,12 @@ Sets the cache mode. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State mode: CacheMode = CacheMode.None build() { Column() { @@ -672,10 +717,12 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State atio: number = 150 build() { Column() { @@ -702,10 +749,12 @@ Sets the scale factor of the entire page. The default value is 100%. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State percent: number = 100 build() { Column() { @@ -732,10 +781,12 @@ Sets the user agent. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36' build() { Column() { @@ -1196,7 +1247,9 @@ This API opens a new window when [multiWindowAccess](#multiwindowaccess9) is ena The default value of **flag** is subject to the settings of the **persist.web.allowWindowOpenMethod.enabled** system attribute. If this attribute is not set, the default value of **flag** is **false**. -To check the settings of **persist.web.allowWindowOpenMethod.enabled**, run the **hdc shell param get persist.web.allowWindowOpenMethod.enabled** command. If the attribute is set to 0 or does not exist, +To check the settings of **persist.web.allowWindowOpenMethod.enabled**, + +run the **hdc shell param get persist.web.allowWindowOpenMethod.enabled** command. If the attribute is set to 0 or does not exist, you can run the **hdc shell param set persist.web.allowWindowOpenMethod.enabled 1** command to enable it. **Parameters** @@ -1256,10 +1309,12 @@ Called when **alert()** is invoked to display an alert dialog box on the web pag ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1314,10 +1369,12 @@ Called when this page is about to exit after the user refreshes or closes the pa ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1375,10 +1432,12 @@ Called when **confirm()** is invoked by the web page. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1435,10 +1494,12 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1495,10 +1556,12 @@ Called to notify the host application of a JavaScript console message. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1532,10 +1595,12 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1569,10 +1634,12 @@ Called when an error occurs during web page loading. For better results, simplif ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1613,10 +1680,12 @@ Called when an HTTP error (the response code is greater than or equal to 400) oc ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1664,10 +1733,12 @@ Called when the web page starts to be loaded. This API is called only for the ma ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1697,10 +1768,12 @@ Called when the web page loading is complete. This API takes effect only for the ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1729,10 +1802,12 @@ Called when the web page loading progress changes. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1761,10 +1836,12 @@ Called when the document title of the web page is changed. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1794,10 +1871,12 @@ Called when loading of the web page is complete. This API is used by an applicat ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1826,10 +1905,12 @@ Called when the rendering process exits abnormally. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1865,10 +1946,12 @@ Called to process an HTML form whose input type is **file**, in response to the ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1914,10 +1997,12 @@ Called to notify the **\** component of the URL of the loaded resource file ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1947,10 +2032,12 @@ Called when the display ratio of this page changes. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -1985,10 +2072,12 @@ Called when the **\** component is about to access a URL. This API is used ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -2024,10 +2113,12 @@ Called when the **\** component is about to access a URL. This API is used ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() responseweb: WebResourceResponse = new WebResourceResponse() heads:Header[] = new Array() @State webdata: string = "\n" + @@ -2095,7 +2186,7 @@ Called when an HTTP authentication request is received. @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() httpAuth: boolean = false build() { @@ -2157,7 +2248,7 @@ Called when an SSL error occurs during resource loading. @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -2207,12 +2298,12 @@ Called when an SSL client certificate request is received. **Example** ```ts - // xxx.ets + // xxx.ets API9 import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -2244,6 +2335,106 @@ Called when an SSL client certificate request is received. } ``` + ```ts + // xxx.ets API10 + import web_webview from '@ohos.web.webview' + import bundle from '@ohos.bundle' + + let uri = ""; + + export default class CertManagerService { + private static sInstance: CertManagerService; + private authUri = ""; + + public static getInstance(): CertManagerService { + if (CertManagerService.sInstance == null) { + CertManagerService.sInstance = new CertManagerService(); + } + return CertManagerService.sInstance; + } + + async grantAppPm(callback) { + let message = ''; + // Note: Replace com.example.myapplication with the actual application name. + let bundleInfo = await bundle.getBundleInfo("com.example.myapplication", bundle.BundleFlag.GET_BUNDLE_DEFAULT) + let clientAppUid = bundleInfo.uid + let appUid = clientAppUid.toString() + + // Note: For globalThis.AbilityContext, add globalThis.AbilityContext = this.context to the onCreate function in the MainAbility.ts file. + await globalThis.AbilityContext.startAbilityForResult( + { + bundleName: "com.ohos.certmanager", + abilityName: "MainAbility", + uri: "requestAuthorize", + parameters: { + appUid: appUid, // UID of the requesting application. + } + }) + .then((data) => { + if (!data.resultCode) { + this.authUri = data.want.parameters.authUri; // Value of authUri returned when authorization is successful. + } + }) + message += "after grantAppPm authUri: " + this.authUri; + uri = this.authUri; + callback(message) + } + } + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State message: string ='Hello World' // message is used for debugging and observation. + certManager = CertManagerService.getInstance(); + + build() { + Row() { + Column() { + Row() { + // Step 1: Perform authorization to obtain the URI. + Button('GrantApp') + .onClick(() => { + this.certManager.grantAppPm((data) => { + this.message = data; + }); + }) + // Step 2: After the authorization, in two-way authentication, the onClientAuthenticationRequest callback is used to send the URI to the web server for authentication. + Button("ClientCertAuth") + .onClick(() => { + this.controller.loadUrl('https://www.example2.com'); // Server website that supports two-way authentication. + }) + } + + Web({ src: 'https://www.example1.com', controller: this.controller }) + .fileAccess(true) + .javaScriptAccess(true) + .domStorageAccess(true) + .onlineImageAccess(true) + + .onClientAuthenticationRequest((event) => { + AlertDialog.show({ + title: 'ClientAuth', + message: 'Text', + confirm: { + value: 'Confirm', + action: () => { + event.handler.confirm(uri); + } + }, + cancel: () => { + event.handler.cancel(); + } + }) + }) + } + } + .width('100%') + .height('100%') + } + } + ``` + ### onPermissionRequest9+ onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) @@ -2260,10 +2451,12 @@ Called when a permission request is received. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2316,10 +2509,12 @@ Shows a context menu after the user clicks the right mouse button or long presse ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2350,10 +2545,12 @@ Called when the scrollbar of the page scrolls. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2383,10 +2580,12 @@ Registers a callback for receiving a request to obtain the geolocation informati ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src:'www.example.com', controller:this.controller }) @@ -2427,10 +2626,12 @@ Called to notify the user that the request for obtaining the geolocation informa ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src:'www.example.com', controller:this.controller }) @@ -2459,10 +2660,12 @@ Called when the component enters full screen mode. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() handler: FullScreenExitHandler = null build() { Column() { @@ -2492,10 +2695,12 @@ Called when the component exits full screen mode. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() handler: FullScreenExitHandler = null build() { Column() { @@ -2525,7 +2730,7 @@ Registers a callback for window creation. | isAlert | boolean | Whether to open the target URL in a new window. The value **true** means to open the target URL in a new window, and **false** means to open the target URL in a new tab.| | isUserTrigger | boolean | Whether the creation is triggered by the user. The value **true** means that the creation is triggered by the user, and **false** means the opposite. | | targetUrl | string | Target URL. | -| handler | [ControllerHandler](#controllerhandler9) | **WebController** instance for setting the new window. | +| handler | [ControllerHandler](#controllerhandler9) | **WebviewController** instance for setting the new window. | **Example** @@ -2566,10 +2771,12 @@ Registers a callback for window closure. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src:'www.example.com', controller: this.controller }) @@ -2599,10 +2806,12 @@ Called to notify the caller of the search result on the web page. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { @@ -2791,6 +3000,84 @@ Called when this web page receives a new favicon. } ``` +### onAudioStateChanged10+ + +onAudioStateChanged(callback: (event: { playing: boolean }) => void) + +Registers a callback for audio playback status changes on the web page. + +**Parameters** + +| Name | Type | Description | +| ------- | ---------------------------------------------- | ----------------------------------- | +| playing | boolean | Audio playback status on the current page. The value **true** means that audio is being played, and **false** means the opposite.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State playing: boolean = false + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onAudioStateChanged(event => { + this.playing = event.playing + console.debug('onAudioStateChanged playing: ' + this.playing) + }) + } + } + } + ``` + +### onLoadIntercept10+ + +onLoadIntercept(callback: (event?: { request: WebResourceRequest }) => boolean) + +Called when the **\** component is about to access a URL. This API is used to determine whether to block the access, which is allowed by default. + +**Parameters** + +| Name | Type | Description | +| ------- | ---------------------------------------- | --------- | +| request | [Webresourcerequest](#webresourcerequest) | Information about the URL request.| + +**Return value** + +| Type | Description | +| ------- | ------------------------ | +| boolean | Returns **true** if the access is blocked; returns **false** otherwise.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onUrlLoadIntercept((event) => { + console.log('url:' + event.request.getRequestUrl()) + console.log('isMainFrame:' + event.request.isMainFrame()) + console.log('isRedirect:' + event.request.isRedirect()) + console.log('isRequestGesture:' + event.request.isRequestGesture()) + return true + }) + } + } + } + ``` + ## ConsoleMessage Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole). @@ -3179,6 +3466,18 @@ Instructs the **\** component to select a file. Implements the **FileSelectorParam** object. For the sample code, see [onShowFileSelector](#onshowfileselector9). +### getTitle9+ + +getTitle(): string + +Obtains the title of this file selector. + +**Return value** + +| Type | Description | +| ------ | -------- | +| string | Title of the file selector.| + ### getMode9+ getMode(): FileSelectorMode @@ -3289,6 +3588,20 @@ Uses the specified private key and client certificate chain. | priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name. | | certChainFile | string | Yes | File that stores the certificate chain, which is a directory including the file name.| +### confirm10+ + +confirm(authUri : string): void + +**Required permissions**: ohos.permission.ACCESS_CERT_MANAGER + +Instructs the **\** component to use the specified credentials (obtained from the certificate management module). + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ------------- | +| authUri | string | Yes | Key value of the credentials. | + ### cancel9+ cancel(): void @@ -3588,7 +3901,148 @@ Sets the geolocation permission status of a web page. | allow | boolean | Yes | - | Geolocation permission status. | | retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions9+](../apis/js-apis-webview.md#geolocationpermissions).| -## WebController +## MessageLevel + +| Name | Description | +| ----- | :---- | +| Debug | Debug level.| +| Error | Error level.| +| Info | Information level.| +| Log | Log level.| +| Warn | Warning level. | + +## RenderExitReason + +Enumerates the reasons why the rendering process exits. + +| Name | Description | +| -------------------------- | ----------------- | +| ProcessAbnormalTermination | The rendering process exits abnormally. | +| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| +| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | +| ProcessOom | The program memory is running low. | +| ProcessExitUnknown | Other reason. | + +## MixedMode + +| Name | Description | +| ---------- | ---------------------------------- | +| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| +| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | +| None | HTTP and HTTPS hybrid content cannot be loaded. | + +## CacheMode +| Name | Description | +| ------- | ------------------------------------ | +| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| +| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | +| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | +| Only | The cache alone is used to load the resources. | + +## FileSelectorMode +| Name | Description | +| -------------------- | ---------- | +| FileOpenMode | Open and upload a file. | +| FileOpenMultipleMode | Open and upload multiple files. | +| FileOpenFolderMode | Open and upload a folder.| +| FileSaveMode | Save a file. | + + ## HitTestType + +| Name | Description | +| ------------- | ------------------------ | +| EditText | Editable area. | +| Email | Email address. | +| HttpAnchor | Hyperlink whose **src** is **http**. | +| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| +| Img | HTML::img tag. | +| Map | Geographical address. | +| Phone | Phone number. | +| Unknown | Unknown content. | + +## SslError9+ + +Enumerates the error codes returned by **onSslErrorEventReceive** API. + +| Name | Description | +| ------------ | ----------- | +| Invalid | Minor error. | +| HostMismatch | The host name does not match. | +| DateInvalid | The certificate has an invalid date. | +| Untrusted | The certificate issuer is not trusted.| + +## ProtectedResourceType9+ + +| Name | Description | Remarks | +| --------- | ------------- | -------------------------- | +| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| + +## WebDarkMode9+ +| Name | Description | +| ------- | ------------------------------------ | +| Off | The web dark mode is disabled. | +| On | The web dark mode is enabled. | +| Auto | The web dark mode setting follows the system settings. | + +## DataResubmissionHandler9+ + +Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. + +### resend9+ + +resend(): void + +Resends the web form data. + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onDataResubmitted((event) => { + console.log('onDataResubmitted') + event.handler.resend(); + }) + } + } + } + ``` + +### cancel9+ + +cancel(): void + +Cancels the resending of web form data. + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onDataResubmitted((event) => { + console.log('onDataResubmitted') + event.handler.cancel(); + }) + } + } + } + ``` + + ## WebController Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. @@ -3600,6 +4054,39 @@ This API is deprecated since API version 9. You are advised to use [WebviewContr webController: WebController = new WebController() ``` +### getCookieManager9+ + +getCookieManager(): WebCookie + +Obtains the cookie management object of the **\** component. + +**Return value** + +| Type | Description | +| --------- | ---------------------------------------- | +| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Button('getCookieManager') + .onClick(() => { + let cookieManager = this.controller.getCookieManager() + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + ### requestFocus(deprecated) requestFocus() @@ -3874,39 +4361,6 @@ This API is deprecated since API version 9. You are advised to use [getHitTest9+ -getTitle(): string - -Obtains the title of the current web page. - -**Return value** - -| Type | Description | -| ------ | -------- | -| string | Title of the current web page.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('getTitle') - .onClick(() => { - let title = this.controller.getTitle() - console.log("title: " + title) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - ### loadData(deprecated) loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) @@ -4303,53 +4757,21 @@ This API is deprecated since API version 9. You are advised to use [clearHistory } ``` -### getCookieManager9+ - -getCookieManager(): WebCookie - -Obtains the cookie management object of the **\** component. - -**Return value** - -| Type | Description | -| --------- | ---------------------------------------- | -| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('getCookieManager') - .onClick(() => { - let cookieManager = this.controller.getCookieManager() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebCookie +## WebCookie(deprecated) Manages behavior of cookies in **\** components. All **\** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. -### setCookie9+ +### setCookie(deprecated) setCookie(url: string, value: string): boolean Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. +This API is deprecated since API version 9. You are advised to use [setCookie9+](../apis/js-apis-webview.md#setcookie) instead. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ----- | ------ | ---- | ---- | ----------------- | -| url | string | Yes | - | URL of the cookie to set.| +| url | string | Yes | - | URL of the cookie to set. A complete URL is recommended.| | value | string | Yes | - | Value of the cookie to set. | **Return value** @@ -4371,7 +4793,7 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if Column() { Button('setCookie') .onClick(() => { - let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b") + let result = this.controller.getCookieManager().setCookie("https://www.example.com", "a=b") console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4379,10 +4801,11 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if } } ``` -### saveCookieSync9+ -saveCookieSync(): boolean +### saveCookie(deprecated) +saveCookie(): boolean Saves the cookies in the memory to the drive. This API returns the result synchronously. +This API is deprecated since API version 9. You are advised to use [saveCookieAsync9+](../apis/js-apis-webview.md#savecookieasync) instead. **Return value** @@ -4401,9 +4824,9 @@ Saves the cookies in the memory to the drive. This API returns the result synchr build() { Column() { - Button('saveCookieSync') + Button('saveCookie') .onClick(() => { - let result = this.controller.getCookieManager().saveCookieSync() + let result = this.controller.getCookieManager().saveCookie() console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4411,144 +4834,3 @@ Saves the cookies in the memory to the drive. This API returns the result synchr } } ``` - -## MessageLevel - -| Name | Description | -| ----- | :---- | -| Debug | Debug level.| -| Error | Error level.| -| Info | Information level.| -| Log | Log level.| -| Warn | Warning level. | - -## RenderExitReason - -Enumerates the reasons why the rendering process exits. - -| Name | Description | -| -------------------------- | ----------------- | -| ProcessAbnormalTermination | The rendering process exits abnormally. | -| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| -| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | -| ProcessOom | The program memory is running low. | -| ProcessExitUnknown | Other reason. | - -## MixedMode - -| Name | Description | -| ---------- | ---------------------------------- | -| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| -| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | -| None | HTTP and HTTPS hybrid content cannot be loaded. | - -## CacheMode -| Name | Description | -| ------- | ------------------------------------ | -| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| -| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | -| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | -| Only | The cache alone is used to load the resources. | - -## FileSelectorMode -| Name | Description | -| -------------------- | ---------- | -| FileOpenMode | Open and upload a file. | -| FileOpenMultipleMode | Open and upload multiple files. | -| FileOpenFolderMode | Open and upload a folder.| -| FileSaveMode | Save a file. | - - ## HitTestType - -| Name | Description | -| ------------- | ------------------------ | -| EditText | Editable area. | -| Email | Email address. | -| HttpAnchor | Hyperlink whose **src** is **http**. | -| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| -| Img | HTML::img tag. | -| Map | Geographical address. | -| Phone | Phone number. | -| Unknown | Unknown content. | - -## SslError9+ - -Enumerates the error codes returned by **onSslErrorEventReceive** API. - -| Name | Description | -| ------------ | ----------- | -| Invalid | Minor error. | -| HostMismatch | The host name does not match. | -| DateInvalid | The certificate has an invalid date. | -| Untrusted | The certificate issuer is not trusted.| - -## ProtectedResourceType9+ - -| Name | Description | Remarks | -| --------- | ------------- | -------------------------- | -| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| - -## WebDarkMode9+ -| Name | Description | -| ------- | ------------------------------------ | -| Off | The web dark mode is disabled. | -| On | The web dark mode is enabled. | -| Auto | The web dark mode setting follows the system settings. | - -## DataResubmissionHandler9+ - -Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. - -### resend9+ - -resend(): void - -Resends the web form data. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController() - build() { - Column() { - Web({ src:'www.example.com', controller: this.controller }) - .onDataResubmitted((event) => { - console.log('onDataResubmitted') - event.handler.resend(); - }) - } - } - } - ``` - -### cancel9+ - -cancel(): void - -Cancels the resending of web form data. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController() - build() { - Column() { - Web({ src:'www.example.com', controller: this.controller }) - .onDataResubmitted((event) => { - console.log('onDataResubmitted') - event.handler.cancel(); - }) - } - } - } - ``` diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 9f858f23a76619be4d0a0e2368a8724ee0fb2ddc..765bafdcd9cb284148d243bc45f18b224f458fb0 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -683,7 +683,7 @@ Fills a rectangle on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.fillRect(0,30,100,100) + this.context.fillRect(30,30,100,100) }) } .width('100%') @@ -1666,10 +1666,15 @@ struct Clip { .backgroundColor('#ffff00') .onReady(() =>{ let region = new Path2D() - region.rect(80,10,20,130) - region.rect(40,50,100,50) + 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() this.context.clip(region,"evenodd") - this.context.fillStyle = "rgb(255,0,0)" + this.context.fillStyle = "rgb(0,255,0)" this.context.fillRect(0, 0, this.context.width, this.context.height) }) } @@ -1918,6 +1923,8 @@ setTransform(transform?: Matrix2D): void Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a void API. +Since API version 9, this API is supported in ArkTS widgets. + ### translate @@ -1973,6 +1980,8 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: Draws an image on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -2349,6 +2358,8 @@ toDataURL(type?: string, quality?: number): string Generates a URL containing image display information. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description | diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index 82628d7048635b4d907c1b933130abc44a40f938..769ac6cfbc8cef5eb1d07376e29f79fea3794915 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -14,6 +14,8 @@ Not supported Canvas(context?: CanvasRenderingContext2D) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -30,7 +32,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name | Parameter | Description | | ----------------------------- | ---- | -------------------- | -| onReady(event: () => void) | - | Triggered when a canvas is ready. When this event is triggered, the width and height of the canvas can be obtained, and you can use the canvas APIs to draw images.| +| onReady(event: () => void) | - | Triggered when a canvas is ready. When this event is triggered, the width and height of the canvas can be obtained, and you can use the canvas APIs to draw images.
Since API version 9, this API is supported in ArkTS widgets.| **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 7c8b95655a9470ea7fd1951132f7b2c7974a45da..3dfd9e208ee1de61b82e2509041469caeef030a9 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -14,6 +14,8 @@ addColorStop(offset: number, color: string): void Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index 2de092ebab7c87d6e21d5fede32ec6c7e7a0f9b5..d6bc06bd61f2de584dc111bdc51a46ea44a94778 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -2,9 +2,21 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. -> **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + +## APIs + +ImageBitmap(src: string) + +Since API version 9, this API is supported in ArkTS widgets. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------------------------------------------ | +| src | string | Yes | - | Image source.
**NOTE**
ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.| @@ -12,8 +24,8 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. | Name| Type| Description| | -------- | -------- | -------- | -| width | number | Pixel width of the **ImageBitmap** object.| -| height | number | Pixel height of the **ImageBitmap** object.| +| width | number | Pixel width of the **ImageBitmap** object.
Since API version 9, this API is supported in ArkTS widgets.| +| height | number | Pixel height of the **ImageBitmap** object.
Since API version 9, this API is supported in ArkTS widgets.| **Example** @@ -54,3 +66,5 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. close() Releases all graphics resources associated with this **ImageBitmap** object. This API is a void API. + +Since API version 9, this API is supported in ArkTS widgets. diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md index a0e91d8853652b63091559dc7cea73df658a2920..7e03641e1383e7df649a64c9a579808840953650 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md @@ -12,9 +12,9 @@ An **ImageData** object stores pixel data rendered on a canvas. | Name| Type| Description| | -------- | -------- | -------- | -| width | number | Actual width of the rectangle on the canvas, in pixels.| -| height | number | Actual height of the rectangle on the canvas, in pixels.| -| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.| +| width | number | Actual width of the rectangle on the canvas, in pixels.
Since API version 9, this API is supported in ArkTS widgets.| +| height | number | Actual height of the rectangle on the canvas, in pixels.
Since API version 9, this API is supported in ArkTS widgets.| +| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.
Since API version 9, this API is supported in ArkTS widgets.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index 9e783167f160f8cdb627d33abaad0ac4212be081..eedbf1762231bd583008cc4ed96bbc544bbb2a63 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -14,13 +14,15 @@ addPath(path: path2D, transform?:Matrix2D): void Adds a path to this path. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | path | path2D | Yes| - | Path to be added to this path.| - | transform | Matrix2D | No| null | Transformation matrix of the new path.| - +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| path | path2D | Yes| - | Path to be added to this path.| +| transform | Matrix2D | No| null | Transformation matrix of the new path.| + **Example** @@ -61,6 +63,8 @@ closePath(): void Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing. +Since API version 9, this API is supported in ArkTS widgets. + **Example** ```ts @@ -101,12 +105,14 @@ moveTo(x: number, y: number): void Moves the current coordinate point of the path to the target point, without drawing a line during the movement. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes| 0 | X-coordinate of the target point.| - | y | number | Yes| 0 | Y-coordinate of the target point.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x | number | Yes| 0 | X-coordinate of the target point.| +| y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -148,12 +154,14 @@ lineTo(x: number, y: number): void Draws a straight line from the current point to the target point. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes| 0 | X-coordinate of the target point.| - | y | number | Yes| 0 | Y-coordinate of the target point.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x | number | Yes| 0 | X-coordinate of the target point.| +| y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -196,16 +204,18 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, Draws a cubic bezier curve on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| - | cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| - | cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| - | cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| - | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| - | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| +| cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| +| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| +| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| +| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| +| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -245,14 +255,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void Draws a quadratic curve on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| - | cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| - | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| - | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| +| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| +| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| +| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -292,16 +304,18 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, Draws an arc on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes| 0 | X-coordinate of the center point of the arc.| - | y | number | Yes| 0 | Y-coordinate of the center point of the arc.| - | radius | number | Yes| 0 | Radius of the arc.| - | startAngle | number | Yes| 0 | Start radian of the arc.| - | endAngle | number | Yes| 0 | End radian of the arc.| - | counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x | number | Yes| 0 | X-coordinate of the center point of the arc.| +| y | number | Yes| 0 | Y-coordinate of the center point of the arc.| +| radius | number | Yes| 0 | Radius of the arc.| +| startAngle | number | Yes| 0 | Start radian of the arc.| +| endAngle | number | Yes| 0 | End radian of the arc.| +| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| **Example** @@ -340,15 +354,17 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void Draws an arc based on the radius and points on the arc. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| - | y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| - | x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| - | y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| - | radius | number | Yes| 0 | Radius of the arc.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| +| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| +| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| +| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| +| radius | number | Yes| 0 | Radius of the arc.| **Example** @@ -387,18 +403,20 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number Draws an ellipse in the specified rectangular region on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes| 0 | X-coordinate of the ellipse center.| - | y | number | Yes| 0 | Y-coordinate of the ellipse center.| - | radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| - | radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| - | rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| - | startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| - | endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| - | counterclockwise | boolean | No| false | Whether to draw the ellipse counterclockwise.
**true**: Draw the ellipse counterclockwise.
**false**: Draw the ellipse clockwise.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x | number | Yes| 0 | X-coordinate of the ellipse center.| +| y | number | Yes| 0 | Y-coordinate of the ellipse center.| +| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| +| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| +| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| +| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| +| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| +| counterclockwise | boolean | No| false | Whether to draw the ellipse counterclockwise.
**true**: Draw the ellipse counterclockwise.
**false**: Draw the ellipse clockwise.| **Example** @@ -437,14 +455,16 @@ rect(x: number, y: number, w: number, h: number): void Creates a rectangle on the canvas. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| - | y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| - | w | number | Yes| 0 | Width of the rectangle.| - | h | number | Yes| 0 | Height of the rectangle.| +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| +| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| +| w | number | Yes| 0 | Width of the rectangle.| +| h | number | Yes| 0 | Height of the rectangle.| **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-components-summary.md b/en/application-dev/reference/arkui-ts/ts-components-summary.md index e83d70ccecae5afbb194451ca6ccc03de75ad0e6..3e5b4706f279043c2d77839cdc7da587faaec3dc 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-summary.md +++ b/en/application-dev/reference/arkui-ts/ts-components-summary.md @@ -109,7 +109,7 @@ - [Button](ts-basic-components-button.md) - A component that can be used to create different types of buttons. + A component that is used to create different types of buttons. - [Toggle](ts-basic-components-toggle.md) A component that provides a clickable element in the check box, button, or switch type. @@ -231,7 +231,7 @@ - [Canvas](ts-components-canvas-canvas.md) - A component that can be used to customize drawings. + A component that is used to customize drawings. - [Circle](ts-drawing-components-circle.md) A component that is used to draw a circle. @@ -262,10 +262,10 @@ - [Web](ts-basic-components-web.md) - A component that can be used to display web pages. + A component that is used to display web pages. -## Miscellaneous +## Miscellaneous - [ScrollBar](ts-basic-components-scrollbar.md) @@ -288,3 +288,15 @@ - [RemoteWindow](ts-basic-components-remotewindow.md) A component that is used to control the application window, providing the component animator and application window linkage animator during application startup and exit. +- [Formcomponent](ts-basic-components-formcomponent.md) + + A component that is used to display widgets. +- [Menu](ts-basic-components-menu.md) + + A component that is used to present a vertical list of items to the user. Preferentially used on computers. +- [MenuItem](ts-basic-components-menuitem.md) + + A component that is used to represent an item in a menu. +- [MenuItemGroup](ts-basic-components-menuitemgroup.md) + + A component that is used to represent a group of menu items. diff --git a/en/application-dev/reference/arkui-ts/ts-container-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 91e41e1a16163adb8ccd9f1d2fdb00d59ebd903f..83529bd0aee34fc253b3d8f46da5fe2cce6b98cc 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -18,6 +18,8 @@ This component supports only one child component. Creates a badge. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -31,6 +33,8 @@ Creates a badge. Creates a badge based on the given string. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -41,6 +45,8 @@ Creates a badge based on the given string. ## BadgePosition +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------- | -------- | | RightTop | The badge is displayed in the upper right corner of the parent component.| @@ -49,6 +55,8 @@ Creates a badge based on the given string. ## BadgeStyle +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory| Default Value | Description | | ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color.White | Font color. | diff --git a/en/application-dev/reference/arkui-ts/ts-container-column.md b/en/application-dev/reference/arkui-ts/ts-container-column.md index 3f39abc38c116009f358d0470200798c7a51bc2c..5f5cf16fe27d23978db2abf3d1ca58c74f926db4 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-column.md +++ b/en/application-dev/reference/arkui-ts/ts-container-column.md @@ -16,6 +16,8 @@ Supported Column(value?: {space?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -28,8 +30,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | Alignment mode of the child components in the horizontal direction.
Default value: **HorizontalAlign.Center**| -| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the vertical direction.
Default value: **FlexAlign.Start**| +| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | Alignment mode of the child components in the horizontal direction.
Default value: **HorizontalAlign.Center**
Since API version 9, this API is supported in ArkTS widgets.| +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the vertical direction.
Default value: **FlexAlign.Start**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md b/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md index 9ebb510cd0e108985bb88287f9f61e6893420498..ca2b63b9a08427a6ea47650948561892db31d210 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md +++ b/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md @@ -26,9 +26,9 @@ ColumnSplit() > **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. > -> Dragging is not supported in the Previewer. Check the drag effect on a real device. +> Dragging is not supported in the Previewer. Check the drag effect on a real device. ## Example @@ -47,6 +47,7 @@ struct ColumnSplitExample { Text('4').width('100%').height(50).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) Text('5').width('100%').height(50).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) } + .borderWidth(1) .resizeable(true) // The divider can be dragged. .width('90%').height('60%') }.width('100%') @@ -54,4 +55,4 @@ struct ColumnSplitExample { } ``` -![en-us_image_0000001212378422](figures/en-us_image_0000001212378422.gif) +![en-us_image_0000001219982708](figures/en-us_image_0000001219982708.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-counter.md b/en/application-dev/reference/arkui-ts/ts-container-counter.md index fe9baa47e05b60a067545c3d6759373b524ee416..69869ef7610fb7359c194afc45da866d5c96df08 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-counter.md +++ b/en/application-dev/reference/arkui-ts/ts-container-counter.md @@ -16,6 +16,8 @@ Supported Counter() +Since API version 9, this API is supported in ArkTS widgets. + ## Events @@ -23,8 +25,8 @@ The universal events and gestures are not supported. Only the following events a | Name| Description| | -------- | -------- | -| onInc(event: () => void) | Invoked when the number of monitored objects is increased.| -| onDec(event: () => void) | Invoked when the number of monitored objects is decreased.| +| onInc(event: () => void) | Invoked when the number of monitored objects is increased.
Since API version 9, this API is supported in ArkTS widgets.| +| onDec(event: () => void) | Invoked when the number of monitored objects is decreased.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index e29fd91fd85ab9142191700d2b73042fe7f77440..6a5908578950850fbedda096b33f03c858097cd0 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -3,7 +3,7 @@ The **\** component allows for flexible layout of child components. > **NOTE** -> +> > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[\](ts-container-column.md)** or **[\](ts-container-row.md)** instead under scenarios where consistently high performance is required. @@ -19,11 +19,13 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle Creates a standard **\** component. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Default Value | Description | | -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | -| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | +| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | diff --git a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md index 33870e0f047cd048aad3f5e1e049da82cbe1202c..cff58a0505258230f3bb60a45ffba2a2c2553c7a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md +++ b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md @@ -13,6 +13,8 @@ This component can contain only one child component. GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColColumnOption, order?: number | GridColColumnOption}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type | Mandatory| Description | @@ -25,12 +27,14 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.
Default value: **1**| -| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid
Default value: **0** | -| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**| +| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| +| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| ## GridColColumnOption +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | xs | number | No | Device of the minimum size. | @@ -38,7 +42,7 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC | md | number | No | Medium-sized device. | | lg | number | No | Large-sized device. | | xl | number | No | Extra-large-sized device. | -| xxl | number | No | Ultra-large-sized device. | +| xxl | number | No | Ultra-large-sized device. | The values of `span`, `offset`, and `order` attributes are inherited in the sequence of `xs`, `sm`, `md`, `lg`, `xl`, and `xxl`. If no value is set for a breakpoint, the value is obtained from the previous breakpoint. diff --git a/en/application-dev/reference/arkui-ts/ts-container-gridrow.md b/en/application-dev/reference/arkui-ts/ts-container-gridrow.md index 8522382eb79c938150837fae77a8067f63f19517..9b246e8755e9df19c31546666cc74720f9cc3798 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-gridrow.md +++ b/en/application-dev/reference/arkui-ts/ts-container-gridrow.md @@ -15,6 +15,8 @@ This component can contain the **\** child component. ## APIs GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | GutterOption, breakpoints?: BreakPoints, direction?: GridRowDirection}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name|Type|Mandatory|Description| @@ -26,6 +28,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt ## GutterOption +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | x | Length \| GridRowSizeOption | No | Gutter in the horizontal direction. | @@ -35,50 +39,62 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt Describes the numbers of grid columns for different device width types. +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | xs | number | No | Device of the minimum size. | -| sm | number | No | Small-sized device. | -| md | number | No | Medium-sized device. | -| lg | number | No | Large-sized device. | -| xl | number | No | Extra-large-sized device. | -| xxl | number | No | Ultra-large-sized device. | +| sm | number | No | Small-sized device. | +| md | number | No | Medium-sized device. | +| lg | number | No | Large-sized device. | +| xl | number | No | Extra-large-sized device. | +| xxl | number | No | Ultra-large-sized device. | ## GridRowSizeOption Describes the gutter sizes for different device width types. +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | xs | Length | No | Device of the minimum size. | -| sm | Length | No | Small-sized device. | -| md | Length | No | Medium-sized device. | -| lg | Length | No | Large-sized device. | -| xl | Length | No | Extra-large-sized device. | -| xxl | Length | No | Ultra-large-sized device. | +| sm | Length | No | Small-sized device. | +| md | Length | No | Medium-sized device. | +| lg | Length | No | Large-sized device. | +| xl | Length | No | Extra-large-sized device. | +| xxl | Length | No | Ultra-large-sized device. | ## BreakPoints +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| value | Array<string> | No | Array of monotonically increasing breakpoints.
Default value: **["320vp", "520vp", "840vp"]** | +| value | Array<string> | No | Array of monotonically increasing breakpoints.
Default value: **["320vp", "600vp", "840vp"]** | | reference | BreakpointsReference | No | Breakpoint switching reference.| ```ts // Enable the xs, sm, and md breakpoints. breakpoints: {value: ["100vp", "200vp"]} // Enable four breakpoints: xs, sm, md, and lg. The breakpoint range must be monotonically increasing. - breakpoints: {value: ["320vp", "520vp", "840vp"]} + breakpoints: {value: ["320vp", "600vp", "840vp"]} // Enable five breakpoints: xs, sm, md, lg, and xl. The number of breakpoint ranges cannot exceed the number of breakpoints minus 1. - breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]} + breakpoints: {value: ["320vp", "600vp", "840vp", "1080vp"]} ``` ## BreakpointsReference + +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------- | -------- | | WindowSize | The window is used as a reference.| | ComponentSize | The container is used as a reference.| ## GridRowDirection + +Since API version 9, this API is supported in ArkTS widgets. + | Name| Description| | -------- | -------- | | Row | Grid elements are arranged in the row direction.| @@ -119,6 +135,8 @@ The [universal attributes](ts-universal-attributes-size.md) are supported. onBreakpointChange(callback: (breakpoints: string) => void) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | 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 7a944fbdedacd17582182a44a8ef03c51f8af141..20754962479003639e3e000f799b42946c3077ad 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -1,6 +1,6 @@ # List -The **\** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text. +The **\** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text. > **NOTE** > @@ -17,6 +17,8 @@ This component supports the **[\](ts-container-listitem.md)** and **[\ List(value?:{space?: number | string, initialIndex?: number, scroller?: Scroller}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -31,20 +33,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.| -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**| -| cachedCount | number | Number of list items or list item groups to be preloaded. A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**| +| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.| +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.| +| cachedCount | number | Number of list items or list item groups to be preloaded. A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| | editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9.
Default value: **false**| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.
Default value: **EdgeEffect.Spring**| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.| -| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\** component.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.| -| alignListItem9+ | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**| -| sticky9+ | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.| +| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\** component.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.
This API is supported in ArkTS widgets.| +| alignListItem9+ | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| +| sticky9+ | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| ## ListItemAlign9+ +This API is supported in ArkTS widgets. + | Name | Description | | ------ | -------------------------------------- | | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| @@ -53,6 +57,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## StickyStyle9+ +This API is supported in ArkTS widgets. + | Name | Description | | ------ | -------------------------------------- | | None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| @@ -66,13 +72,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Description| | -------- | -------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| -| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset.
- **[scrollState](#scrollstate)**: current scroll state.| -| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.
When calculating the index value, the **\** accounts for one index value as a whole, and the index values of the list items within are not calculated.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.| -| onReachStart(event: () => void) | Triggered when the list reaches the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.| -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current sliding status.
- **offsetRemain**: required amount to scroll by in the horizontal direction.| -| onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).| -| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).| +| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset.
- **[scrollState](#scrollstate)**: current scroll state.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.
When calculating the index value, the **\** accounts for one index value as a whole, and the index values of the list items within are not calculated.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
Since API version 9, this API is supported in ArkTS widgets.| +| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls.
This API is supported in ArkTS widgets.| +| onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| +| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).| @@ -82,6 +88,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## ScrollState +Since API version 9, this API is supported in ArkTS widgets. + | Name | Description | | ------ | ------------------------- | | Idle | Not scrolling. | diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index a101532880cdab858319d8a13cf7df487cfb3a33..c5bb7c662b007a3cd5b186ecf2c910efef2362ef 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -16,6 +16,8 @@ This component can contain a single child component. ListItem(value?: string) +Since API version 9, this API is supported in ArkTS widgets. + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. @@ -24,7 +26,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | -------- | -------- | -------- | | sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component.| | editable(deprecated) | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.
This API is deprecated since API version 9.
Default value: **false**| -| selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| +| selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| | swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Component displayed when the list item is swiped out from the screen edge.
- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).
- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
| ## Sticky(deprecated) @@ -53,7 +55,7 @@ This API is deprecated since API version 9. | Name| Description| | -------- | -------- | -| onSelect(event: (isSelected: boolean) => void)8+ | Triggered when the selected state of the **\** changes.
**isSelected**: Returns **true** if the **\** is selected by mouse drag; returns **false** otherwise.| +| onSelect(event: (isSelected: boolean) => void)8+ | Triggered when the selected state of the **\** changes.
**isSelected**: Returns **true** if the **\** is selected by mouse drag; returns **false** otherwise.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-navigator.md b/en/application-dev/reference/arkui-ts/ts-container-navigator.md index e1d2c00f81527d3303b45031d858b76f9537099b..f5c24ce3043f17193050c767bcd8a55ee647779b 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-navigator.md +++ b/en/application-dev/reference/arkui-ts/ts-container-navigator.md @@ -27,9 +27,9 @@ Navigator(value?: {target: string, type?: NavigationType}) | Name | Description | | ------- | -------------------------- | -| Push | Navigates to a specified page in the application. | +| Push | Navigates to the specified page in the application. | | Replace | Replaces the current page with another one in the application and destroys the current page.| -| Back | Returns to the previous page or a specified page. | +| Back | Returns to the specified page. If the specified page does not exist in the stack, no response is returned. If no page is specified, the previous page is returned to.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md index f0e9f85f122e630c6f73f5443d0d4260abaaf5cf..77f136b9f2c9de3a7e59cb69c017ba33df6b6a10 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md @@ -31,6 +31,8 @@ Multiple child components are supported. RelativeContainer() +Since API version 9, this API is supported in ArkTS widgets. + ## Example ```ts 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 deb83273445d1b5d16e5540476ccfa9c8c9b1fba..606759b76c1d63dda9ebabcfffaeec5f11f833c7 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-row.md +++ b/en/application-dev/reference/arkui-ts/ts-container-row.md @@ -16,6 +16,8 @@ Supported Row(value?:{space?: number | string }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -27,8 +29,8 @@ 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 | +| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Alignment mode of child components in the vertical direction.
Default value: **VerticalAlign.Center**
Since API version 9, this API is supported in ArkTS widgets.| +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.
FlexAlign.Start
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 1ebba8cc427bd9205fa7048310d9e97274f079ea..b8b88e630b72e4499498f066beadc8cd197f8059 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -18,6 +18,12 @@ This component supports only one child component. Scroll(scroller?: Scroller) +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| scroller | [Scroller](#scroller) | No| Scroller, which can be bound to scrollable components.| + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. @@ -42,12 +48,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: required amount to scroll by in the horizontal direction.| +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: actual amount by which the component scrolls.| | onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | | onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge. | -| onScrollEnd(event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead. | -| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).| -| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).| +| onScrollEnd(deprecated) (event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead. | +| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.| +| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.| > **NOTE** > @@ -111,7 +117,7 @@ Scrolls to the next or previous page. ### currentOffset -currentOffset() +currentOffset(): { xOffset: number, yOffset: number } Obtains the scrolling offset. diff --git a/en/application-dev/reference/arkui-ts/ts-container-stack.md b/en/application-dev/reference/arkui-ts/ts-container-stack.md index 66dcd7deb957887e5ca627464de88148b1897fe7..1170de852ec2fd8c3361d4bd19a4cb5fc1f44231 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-stack.md +++ b/en/application-dev/reference/arkui-ts/ts-container-stack.md @@ -16,11 +16,21 @@ Supported Stack(value?: { alignContent?: Alignment }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| alignContent | [Alignment](ts-appendix-enums.md#alignment) | No| Alignment of child components in the container.
Default value: **Alignment.Center**| +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------- | ---- | ----------------------------------------------------------- | +| alignContent | [Alignment](ts-appendix-enums.md#alignment) | No | Alignment of child components in the container.
Default value: **Alignment.Center**| + +## Attributes + +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + +| Name | Type | Description | +| ------------ | ------------------------------------------- | ------------------------------ | +| alignContent | [Alignment](ts-appendix-enums.md#alignment) | Alignment of child components in the container.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 849218cf45e69fd423b020dd8dd26381933c1fe3..2f224afc0377281c20ee36a638b5862a39096106 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | --------------------------- | ---------------------------------------- | ---------------------------------------- | | index | number | Index of the child component currently displayed in the container.
Default value: **0** | -| autoPlay | boolean | Whether to enable automatic playback for child component switching. If this attribute is **true**, the navigation dots indicator does not take effect.
Default value: **false** | +| autoPlay | boolean | Whether to enable automatic playback for child component switching.
Default value: **false** | | interval | number | Interval for automatic playback, in ms.
Default value: **3000** | | indicator | boolean | Whether to enable the navigation dots indicator.
Default value: **true** | | loop | boolean | Whether to enable loop playback.
The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.
Default value: **true**| 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 d874d686fd63a1e00b2892ec5d24a7e069786e02..6b6a994a6f4e5ea976e96c87a366c501479383c4 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -29,6 +29,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the > **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. > - The **\** component does not support setting of the common height attribute. Its height is determined by the height of the parent **\** component and the **\** component. +> - **\** does not support page scrolling. If page scrolling is required, consider nesting a list. ## SubTabBarStyle9+ diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md index 1c17cda5d9d55a722cbf3351b3a72586d224c346..c69ca31dbccaa9f3246500d1b5baa92cc50718bc 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md @@ -16,6 +16,8 @@ Not supported Circle(options?: {width?: string | number, height?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -29,17 +31,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | Color of the fill area.
Default value: **Color.Black**| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| Opacity of the fill area.
Default value: **1**| -| stroke | [ResourceColor](ts-types.md) | Stroke color. If this attribute is not set, the component does not have any stroke.| -| strokeDashArray | Array<Length> | Stroke dashes.
Default value: **[]** | -| strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.
Default value: **0**| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.
Default value: **LineCapStyle.Butt**| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.
Default value: **LineJoinStyle.Miter**| -| strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
Default value: **4**
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.
Default value: **1**
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | Stroke width.
Default value: **1**| -| antiAlias | boolean | Whether anti-aliasing is enabled.
Default value: **true**| +| fill | [ResourceColor](ts-types.md) | Color of the fill area.
Default value: **Color.Black**
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| Opacity of the fill area.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | Stroke dashes.
Default value: **[]**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.
Default value: **LineCapStyle.Butt**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.
Default value: **LineJoinStyle.Miter**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
Default value: **4**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| +| strokeWidth | Length | Stroke width.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | Whether anti-aliasing is enabled.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md index 019f2f008a634f1aee6f1a90d1028b3c69cbd30f..c8249cf5a97811d42832fd262c1eee1d3bc2e985 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md @@ -16,6 +16,8 @@ Not supported Ellipse(options?: {width?: string | number, height?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Description| @@ -29,17 +31,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Example 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 724c976b06687a818a0456d9fdd4b845a4ea85ab..a8097c5e449d613a378643fef8902abe41be6bba 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 @@ -15,6 +15,8 @@ Not supported Line(value?: {width?: string | number, height?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -29,19 +31,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| startPoint | Array<Length> | [0, 0] | Coordinates (relative coordinates) of the start point of the line, in vp.| -| endPoint | Array<Length> | [0, 0] | Coordinates (relative coordinates) of the end point of the line, in vp.| -| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | Color of the fill area.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a closed shape.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a closed shape.| -| stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | Stroke color.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a shape with a sharp angle.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| startPoint | Array<Length> | [0, 0] | Coordinates (relative coordinates) of the start point of the line, in vp.
Since API version 9, this API is supported in ArkTS widgets.| +| endPoint | Array<Length> | [0, 0] | Coordinates (relative coordinates) of the end point of the line, in vp.
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a closed shape.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a closed shape.| +| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a shape with a sharp angle.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -58,6 +60,7 @@ struct LineExample { Line() .startPoint([0, 0]) .endPoint([50, 100]) + .stroke(Color.Black) .backgroundColor('#F5F5F5') Line() .width(200) @@ -72,6 +75,7 @@ struct LineExample { Line({ width: 50, height: 50 }) .startPoint([0, 0]) .endPoint([100, 100]) + .stroke(Color.Black) .strokeWidth(3) .strokeDashArray([10, 3]) .backgroundColor('#F5F5F5') @@ -79,6 +83,7 @@ struct LineExample { Line({ width: 50, height: 50 }) .startPoint([0, 0]) .endPoint([100, 100]) + .stroke(Color.Black) .strokeWidth(3) .strokeDashArray([10, 3]) .strokeDashOffset(5) @@ -105,6 +110,7 @@ struct LineExample1 { .height(200) .startPoint([50, 50]) .endPoint([50, 200]) + .stroke(Color.Black) .strokeWidth(20) .strokeLineCap(LineCapStyle.Butt) .backgroundColor('#F5F5F5').margin(10) @@ -114,6 +120,7 @@ struct LineExample1 { .height(200) .startPoint([50, 50]) .endPoint([50, 200]) + .stroke(Color.Black) .strokeWidth(20) .strokeLineCap(LineCapStyle.Round) .backgroundColor('#F5F5F5') @@ -123,6 +130,7 @@ struct LineExample1 { .height(200) .startPoint([50, 50]) .endPoint([50, 200]) + .stroke(Color.Black) .strokeWidth(20) .strokeLineCap(LineCapStyle.Square) .backgroundColor('#F5F5F5') @@ -145,29 +153,34 @@ struct LineExample { Line() .startPoint([50, 30]) .endPoint([300, 30]) + .stroke(Color.Black) .strokeWidth(10) // Set the interval for strokeDashArray to 50. Line() .startPoint([50, 20]) .endPoint([300, 20]) + .stroke(Color.Black) .strokeWidth(10) .strokeDashArray([50]) // Set the interval for strokeDashArray to 50, 10. Line() .startPoint([50, 20]) .endPoint([300, 20]) + .stroke(Color.Black) .strokeWidth(10) .strokeDashArray([50, 10]) // Set the interval for strokeDashArray to 50, 10, 20. Line() .startPoint([50, 20]) .endPoint([300, 20]) + .stroke(Color.Black) .strokeWidth(10) .strokeDashArray([50, 10, 20]) // Set the interval for strokeDashArray to 50, 10, 20, 30. Line() .startPoint([50, 20]) .endPoint([300, 20]) + .stroke(Color.Black) .strokeWidth(10) .strokeDashArray([50, 10, 20, 30]) diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index f0645c5079ef86d29d848e059c5187bf76f5d8d3..313e416b8be00dff249f60ff55af2337a81c889c 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -15,6 +15,8 @@ Not supported Path(value?: { width?: number | string; height?: number | string; commands?: string }) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory| Description | @@ -29,18 +31,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Default Value | Description | | -------- | ----------------------------------- | ---- | ---------------------------------------- | -| commands | string | '' | Command for drawing the path. The unit is px. For details about how to convert pixel units, see [Pixel Units](ts-pixel-units.md).| -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - | Stroke color.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Width of the stroke.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| commands | string | '' | Command for drawing the path. The unit is px. For details about how to convert pixel units, see [Pixel Units](ts-pixel-units.md).
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Width of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| The supported commands are as follows: 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 c8c45849bc38492435bee3aa441af82913bb519d..d126f92b224838ffb413cd58b0ad1f287300d184 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,6 +16,8 @@ Not supported Polygon(value?: {width?: string | number, height?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -30,23 +32,25 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | Vertex coordinates of the polygon.| -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| points | Array<Point> | [] | Vertex coordinates of the polygon.
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Point Describes the coordinates of a point. +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | --------- | -------------------- | ------------------------------------------------------------ | | Point | [number, number] | Coordinates of a point. The first parameter is the x-coordinate, and the second parameter is the y-coordinate (relative coordinate).| 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 739ca2b19aa78128b2154db9df778bb65dfe9ba9..4e5d746283be0023fe1951fa12a81d8cfdec398a 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,6 +16,8 @@ Not supported Polyline(value?: {width?: string | number, height?: string | number}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -30,23 +32,25 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | List of coordinates that the polyline passes through.| -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - | Stroke color.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| points | Array<Point> | [] | List of coordinates that the polyline passes through.
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Point Describes the coordinates of a point. +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | --------- | -------------------- | ------------------------------------------------------------ | | Point | [number, number] | Coordinates of a point. The first parameter is the x-coordinate, and the second parameter is the y-coordinate (relative coordinate).| 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 e05fad3fd06045b8a6a4641c308378f1caaafbb7..f6ce5646c2893449a91080a30eeb635949d42f50 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,6 +17,8 @@ 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}) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -34,20 +36,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| radiusWidth | string \| number | 0 | Width of the rounded corner. The width and height are the same when only the width is set.| -| radiusHeight | string \| number | 0 | 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 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.| -| strokeDashArray | Array<Length> | [] | Stroke dashes. | -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| +| radiusWidth | string \| number | 0 | Width of the rounded corner. The width and height are the same when only the width is set.
Since API version 9, this API is supported in ArkTS widgets.| +| radiusHeight | string \| number | 0 | Height of the rounded corner. The width and height are the same only when the height is set.
Since API version 9, this API is supported in ArkTS widgets.| +| radius | string \| number \| Array<string \| number> | 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -84,6 +86,7 @@ struct RectExample { Rect({ width: '90%', height: 80 }) .radius(20) .fill(Color.Pink) + .stroke(Color.Transparent) }.width('100%').margin({ top: 10 }) // Draw a 90% x 50 rectangle, with the width and height of its rounded corners as follows: 40 for the upper left rounded corner, 20 for the upper right rounded corner, 40 for the lower right rounded corner, and 20 for the lower left rounded corner. Rect({ width: '90%', height: 80 }) 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 5cb117bb123247c736fc870db245c59f6187e41a..0444767799d78e070b7d2bb1aec631189587c5b2 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,6 +21,8 @@ The following child components are supported: **[\](ts-drawing-components- Shape(value?: PixelMap) +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name| Type| Mandatory| Default Value| Description| @@ -34,19 +36,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | View port of the shape.| -| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.| -| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.| -| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.| -| strokeDashArray | Array<Length> | [] | Stroke dashes.| -| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.| -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.| -| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.| -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | number \| string | 1 | Stroke width.| -| antiAlias | boolean | true | Whether anti-aliasing is enabled.| -| mesh8+ | Array<number>,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.| +| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | View port of the shape.
Since API version 9, this API is supported in ArkTS widgets.| +| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| +| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | number \| string | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| +| mesh8+ | Array<number>,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md index b2802444ab2e297ffc599263910afea57fee2465..1cee9be56077b524b2bb71e098336701e7dd9593 100644 --- a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -6,9 +6,10 @@ You can create explicit animation with your custom settings. > > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - animateTo(value: AnimateParam, event: () => void): void +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ---------------- | ------------ | -------------------- | -------------------- | | value | [AnimateParam](#animateparam)| Yes| Animation settings.| @@ -18,13 +19,13 @@ animateTo(value: AnimateParam, event: () => void): void | Name| Type| Description| | -------- | -------- | -------- | -| duration | number | Animation duration, in ms.
Default value: **1000**| +| duration | number | Animation duration, in ms.
Default value: **1000**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
- The maximum animation duration on an ArkTS widget is 1000 ms. If the set value exceeds the limit, the value **1000** will be used.| | tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.
Default value: **1.0**| -| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.
Default value: **Curve.Linear**| +| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.
Default value: **Curve.Linear**
Since API version 9, this API is supported in ArkTS widgets.| | delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.
Default value: **0**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| -| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**| -| onFinish | () => void | Callback invoked when the animation playback is complete.| +| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**
Since API version 9, this API is supported in ArkTS widgets.| +| onFinish | () => void | Callback invoked when the animation playback is complete.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 37bf4de513a5773e660b53d8a07c621882c21714..56ebc03a81c7873468f9164e8b7ab90e8de70571 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -11,7 +11,7 @@ A custom dialog box is a dialog box you customize by using APIs of the **CustomD ## APIs -CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam}) +CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam, showInSubWindow?: boolean}) **Parameters** @@ -26,8 +26,9 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | customStyle | boolean | No | Whether to use a custom style for the dialog box.
Default value: **false**, which means that the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height; the rounded corner is 24 vp. | | gridCount8+ | number | No | Number of [grid columns](../../ui/ui-ts-layout-grid-container-new.md) occupied by the dialog box.
The default value is 4, and the maximum value is the maximum number of columns supported by the system. If this parameter is set to an invalid value, the default value is used.| | maskColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Custom mask color.
Default value: **0x33000000** | -| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box. | +| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box.
**NOTE**
If **iterations** is set to an odd number and **playMode** is set to **Reverse**, the dialog box will not be displayed when the animation ends. | | closeAniamtion10+| [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the close animation of the dialog box. | +| showInSubWindow10+| boolean | No | Whether to display a dialog box in a subwindow.
Default value: **false**, indicating that the dialog box is not displayed in the subwindow
**NOTE**
A dialog box whose **showInSubWindow** attribute is **true** cannot trigger the display of another dialog box whose **showInSubWindow** attribute is also **true**. | ## CustomDialogController @@ -108,6 +109,11 @@ struct CustomDialogUser { customStyle: false }) + aboutToDisappear() { + delete this.dialogController, + this.dialogController = undefined + } + onCancel() { console.info('Callback when the first button is clicked') } @@ -124,7 +130,9 @@ struct CustomDialogUser { Column() { Button(this.inputValue) .onClick(() => { - this.dialogController.open() + if (this.dialogController != undefined) { + this.dialogController.open() + } }).backgroundColor(0x317aff) }.width('100%').margin({ top: 5 }) } diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 0f7d462061595e1d78647dd6e93dbd0b18f6585e..9aa9657ae94666cded17944174a3574223e46a77 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -727,7 +727,7 @@ Fills a rectangle on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillRect(0,30,100,100) + this.offContext.fillRect(30,30,100,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1767,10 +1767,15 @@ struct Clip { .backgroundColor('#ffff00') .onReady(() =>{ let region = new Path2D() - region.rect(80,10,20,130) - region.rect(40,50,100,50) + 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() this.offContext.clip(region,"evenodd") - this.offContext.fillStyle = "rgb(255,0,0)" + this.offContext.fillStyle = "rgb(0,255,0)" this.offContext.fillRect(0, 0, 600, 600) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -2407,6 +2412,8 @@ toDataURL(type?: string, quality?: number): string Generates a URL containing image display information. +Since API version 9, this API is supported in ArkTS widgets. + **Parameters** | Name | Type | Mandatory | Description | diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 2256aa963c944561e69ccbf110a656347afd448a..4f7099cc28fffbe5b72c6fa3ddd5fe0cfa1b969f 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -8,21 +8,21 @@ The framework provides four pixel units, with vp as the reference data unit. | px | Physical pixel unit of the screen. | | vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified.| | fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.| ## Pixel Unit Conversion Conversion between px and other pixel units is supported. -| API | Description | -| ---------------------------------------- | ---------------------- | -| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | -| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | -| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | -| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | -| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px.| -| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx.| +| API | Description | +| --------------------------------------------------- | ------------------------------------------------------------ | +| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp.
Since API version 9, this API is supported in ArkTS widgets.| +| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp.
Since API version 9, this API is supported in ArkTS widgets.| +| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-types.md b/en/application-dev/reference/arkui-ts/ts-types.md index ffc46108ad8944d16f354ef022581cca6494f0a0..78d1c4fb2c2fc836b19e1ea17e96c662f72075c7 100644 --- a/en/application-dev/reference/arkui-ts/ts-types.md +++ b/en/application-dev/reference/arkui-ts/ts-types.md @@ -128,6 +128,14 @@ The **ResourceColor** type is used to describe the color types of resources. | string | Color in RGB or RGBA notation. | | [Resource](#resource) | Color referenced from system or application resources.| +## ColoringStrategy + +The **ColoringStrategy** type is used to describe the foreground colors. + +| Name | Description | +| --------- | ------- | +| Invert | Inverse of the component background color.| + ## LengthConstrain The **LengthConstrain** type is used to describe the maximum and minimum lengths of a component. 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 0bde935d8e104ad982c322c342abb71b96909a31..98da7c61fee51c2a6d99349a7de61b93fda1cede 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ You can set the background of a component. | Name| Type| Description| | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.| -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **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, that is, the coordinates relative to the upper left corner of the component.
Default value:
{
x: 0,
y: 0
}
When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.
Since API version 9, this API is supported in ArkTS widgets.| +| 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.
Since API version 9, this API is supported in ArkTS widgets.| +| 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**
Since API version 9, this API is supported in ArkTS widgets.| +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.
Default value:
{
x: 0,
y: 0
}
When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.
Since API version 9, this API is supported in ArkTS widgets.| ## 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 e24e391a4690c7767dd9449c4ef5d1e6d2daa968..fdff66a475bb3987ab7574b14d99fe0ea50a6ff0 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 @@ -12,10 +12,12 @@ You can apply background blur effects to a component. | Name | Type | Description | | -------------------- | ----------------------- | ------------------------ | -| backgroundBlurStyle | [BlurStyle](#blurstyle) | Style of the blur between the background and content for the current component. The input parameter indicates a blur material.| +| backgroundBlurStyle | [BlurStyle](#blurstyle) | Style of the blur between the background and content for the current component. The input parameter indicates a blur material.
This API is supported in ArkTS widgets.| ## BlurStyle +This API is supported in ArkTS widgets. + | Name | Description | | ------- | ---------- | | Thin | Thin material. | diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index d50f5ec504c3b9f215e033c4d33dd9dc48dba96d..2371633764347fc20d9306e52a561ecb98795a63 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -10,10 +10,12 @@ You can draw an image around a component. | Name | Type | Description | | ---------- | ---------------------------------------- | --------------------------------------- | -| borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient. | +| borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient.
This API is supported in ArkTS widgets.| ## BorderImageOption +This API is supported in ArkTS widgets. + | Name | Type | Description | | ---------- | ---------------------------------------- | --------------------------------------- | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.
**NOTE**
The border image source applies only to container components, such as **\**, **\**, and **\**.| @@ -23,9 +25,10 @@ You can draw an image around a component. | repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.
Default value: **RepeatMode.Stretch**| | fill | boolean | Whether to fill the center of the border image.
Default value: **false** | - ## RepeatMode +This API is supported in ArkTS widgets. + | Name | Description | | ------- | ----------------------------------- | | Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped. | diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border.md index 5387323038344bdea0670d857178ad6ae4175ac5..2868a7fdf9c6920437dbd6d105051bd6c2f94f88 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border.md @@ -13,11 +13,11 @@ The border attributes are used to set border styles for components. | Name | Type | Description | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| border | {
width?: [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9)9+,
color?: [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9)9+,
radius?: [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9)9+,
style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9)9+
} | Unified border style.
- **width**: border width.
- **color**: border color.
- **radius**: radius of the rounded corner of the border.
- **style**: border style.| -| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9)9+ | Border style.
Default value: **BorderStyle.Solid** | -| borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9)9+ | Border width. The percentage format is not supported. | -| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9)9+ | Border color.
Default value: **Color.Black** | -| borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9)9+ | Border radius. The percentage format is not supported. | +| border | {
width?: [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9)9+,
color?: [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9)9+,
radius?: [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9)9+,
style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9)9+
} | Unified border style.
- **width**: border width.
- **color**: border color.
- **radius**: radius of the rounded corner of the border.
- **style**: border style.
Since API version 9, this API is supported in ArkTS widgets.| +| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9)9+ | Border style.
Default value: **BorderStyle.Solid**
Since API version 9, this API is supported in ArkTS widgets.| +| borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9)9+ | Border width. The percentage format is not supported.
Since API version 9, this API is supported in ArkTS widgets.| +| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9)9+ | Border color.
Default value: **Color.Black**
Since API version 9, this API is supported in ArkTS widgets.| +| borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9)9+ | Border radius. The percentage format is not supported.
Since API version 9, this API is supported in ArkTS widgets.| ## EdgeWidths9+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index 72c361558b417f77d28024abda69e19bc7ad111e..1c96d9b4d0ed36fabb1069bd42eb1ac1a1965b6c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -11,7 +11,7 @@ | Name | Type | Description | | -----| -------- | ----------------------------- | -| id | string | Unique ID you assigned to the component.
Default value: **''**| +| id | string | Unique ID you assigned to the component.
Default value: **''**
Since API version 9, this API is supported in ArkTS widgets.| ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md index 6e7645eabe12366ced89fb469334612d2205bd9f..d30aa033b3dd9276a78d1b47f639661d384d5a7c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md @@ -10,9 +10,9 @@ The **enabled** attribute sets whether a component responds to user interactions ## Attributes -| Name | Type | Description | -| ------- | ------- | ---------------------------------------- | -| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions, and **false** means the opposite.
Default value: **true** | +| Name | Type| Description | +| ------- | -------- | ------------------------------------------------------------ | +| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions, and **false** means the opposite.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index 9234810c88d381fbeda3bbc8e9b79a244d5f74ac..702fdef1d7c4acb9f3a2bc8eecd9325ec4367181 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -8,12 +8,12 @@ ## Attributes -| Name | Type | Description | -| ---------- | ---------------------------------------- | ---------------------------------------- | -| flexBasis | number \| string | Base size of the component in the main axis of the parent container.
Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)
This attribute cannot be set in percentage.| -| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.
Default value: **0** | -| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.
When the parent container is **\** or **\**, the default value is **0**.
When the parent container is **\**, the default value is **1**. | -| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container.
Default value: **ItemAlign.Auto**| +| Name | Type | Description | +| ---------- | ------------------------------------------- | ------------------------------------------------------------ | +| flexBasis | number \| string | Base size of the component in the main axis of the parent container.
Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)
This attribute cannot be set in percentage.
Since API version 9, this API is supported in ArkTS widgets.| +| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.
When the parent container is **\** or **\**, the default value is **0**.
When the parent container is **\**, the default value is **1**.
Since API version 9, this API is supported in ArkTS widgets.| +| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container.
Default value: **ItemAlign.Auto**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md new file mode 100644 index 0000000000000000000000000000000000000000..cfa2a0310f83db2933638297865c0f1674ea07b5 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md @@ -0,0 +1,75 @@ +# Foreground Color + +The foreground color attributes set the foreground color of a component. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Attributes + +| Name| Type| Description| +| -------- | -------- | -------- | +| foregroundColor | [ResourceColor](ts-types.md#resourcecolor) \| [ColoringStrategy](ts-types.md#coloringstrategy) | Foreground color. The value can be a specific color or a coloring strategy.| + +## Example + +### Example 1 +```ts +// xxx.ets +@Entry +@Component +struct ForegroundColorExample { + build() { + Column({ space: 100 }) { + // Draw a circle with a diameter of 150 and the default fill color black. + Circle({ width: 150, height: 200 }) + // Draw a circle with a diameter of 150. + Circle({ width: 150, height: 200 }).foregroundColor(Color.Red) + }.width('100%').backgroundColor(Color.Blue) + } +} +``` + +![foregroundColor_circle](figures/foregroundColor_circle.png) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct ColoringStrategyExample { + build() { + Column({ space: 100 }) { + // Draw a circle with a diameter of 150 and the default fill color black. + Circle({ width: 150, height: 200 }) + // Draw a circle with a diameter of 150 and set its foreground color to the inverse of the component background color. + Circle({ width: 150, height: 200 }) + .backgroundColor(Color.Black) + .foregroungColor(ColoringStrategy.Invert) + }.width('100%') + } +} +``` + +![foregroundColor_circle](figures/ColoringStrategy_circle.png) + +### Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct foregroundColorInherit { + build() { + Column() { + Button('Foreground Color Set to Orange').fontSize(20).foregroundColor(Color.Orange).backgroundColor(Color.Gray) + Divider() + Button ('Foreground Color Inherited from Parent Component When Not Set').fontSize(20).backgroundColor(Color.Gray) + }.foregroundColor(Color.Red) + } +} +``` + +![foregroundColor_circle](figures/foregroundColorInherit.jpg) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md index a8db3e77829f493a331e570449b80cedce5eb2b2..b989c3554a0c0725688fbd44b2aed9fc95d99022 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md @@ -12,9 +12,9 @@ Create a more gorgeous look for a component by applying a gradient color effect | Name | Type | Description | | -------------- | -------------------------------------------- | ----------------------------------- | -| linearGradient | {
angle?: number \| string,
direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Linear gradient.
- **angle**: start angle of the linear gradient. A positive value indicates a clockwise rotation from the origin, (0, 0).
Default value: **180**
- **direction**: direction of the linear gradient. It does not take effect when **angle** is set.
Default value: **GradientDirection.Bottom**
- **colors**: colors of the linear gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**| -| sweepGradient | {
center: Point,
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Angle gradient.
- **center**: center point of the angle gradient, that is, the coordinates relative to the upper left corner of the current component.
- **start**: start point of the angle gradient.
Default value: **0**
- **end**: end point of the angle gradient.
Default value: **0**
- **rotation**: rotation angle of the angle gradient.
Default value: **0**
- **colors**: colors of the angle gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**| -| radialGradient | {
center: Point,
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Radial gradient.
- **center**: center point of the radial gradient, that is, the coordinates relative to the upper left corner of the current component.
- **radius**: radius of the radial gradient.
- **colors**: colors of the radial gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**| +| linearGradient | {
angle?: number \| string,
direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Linear gradient.
- **angle**: start angle of the linear gradient. A positive value indicates a clockwise rotation from the origin, (0, 0).
Default value: **180**
- **direction**: direction of the linear gradient. It does not take effect when **angle** is set.
Default value: **GradientDirection.Bottom**
- **colors**: colors of the linear gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| sweepGradient | {
center: Point,
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Sweep gradient, which can sweep around the specified center point in the 0–360 degree range. If the rotation angle exceeds the range, a monochrome color instead of a gradient will be drawn.
- **center**: center point of the sweep gradient, that is, the coordinates relative to the upper left corner of the current component.
- **start**: start point of the sweep gradient.
Default value: **0**
- **end**: end point of the sweep gradient.
Default value: **0**
- **rotation**: rotation angle of the sweep gradient.
Default value: **0**
- **colors**: colors of the sweep gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| radialGradient | {
center: Point,
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Radial gradient.
- **center**: center point of the radial gradient, that is, the coordinates relative to the upper left corner of the current component.
- **radius**: radius of the radial gradient.
- **colors**: colors of the radial gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| ## 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 69272c0d3bf0283b23e894da1342649e6c612472..4d4e1e7440c93e9b80972d5582b0edfe8800a176 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 @@ -3,6 +3,7 @@ Image effects include blur, shadow, and much more. > **NOTE** +> > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -11,17 +12,41 @@ Image effects include blur, shadow, and much more. | Name | Type | Default Value| Description | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | -| blur | number | - | Applies 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 | - | Applies 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](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource),
offsetX?: number \| [Resource](ts-types.md#resource),
offsetY?: number \| [Resource](ts-types.md#resource)
} | - | Applies 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 | Applies 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.| -| saturate | number | 1.0 | Applies the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage.| -| contrast | number | 1.0 | Applies the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage.| -| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage.| -| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage.| -| hueRotate | number \| string | '0deg' | Applies the hue rotation effect to the current component. The input parameter is a rotation angle. | -| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | Applies the color blend effect to the current component. The input parameter is the blended color. | +| blur | number | - | Applies 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.
Since API version 9, this API is supported in ArkTS widgets.| +| backdropBlur | number | - | Applies 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.
Since API version 9, this API is supported in ArkTS widgets.| +| shadow | [ShadowOptions](#shadowoptions) \| [ShadowStyle](#shadowstyle10) | - | Applies a shadow effect to the current component.
When the value type is **ShadowOptions**, the blur radius, shadow color, and offset along the x-axis and y-axis can be specified.
When the value type is **ShadowStyle**, the shadow style can be specified.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
ArkTS widgets do not support the [ShadowStyle](#shadowstyle10) value type. | +| 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.
Since API version 9, this API is supported in ArkTS widgets.| +| brightness | number | 1.0 | Applies 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.
Since API version 9, this API is supported in ArkTS widgets.| +| saturate | number | 1.0 | Applies the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage.
Since API version 9, this API is supported in ArkTS widgets.| +| contrast | number | 1.0 | Applies the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage.
Since API version 9, this API is supported in ArkTS widgets.| +| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage.
Since API version 9, this API is supported in ArkTS widgets.| +| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage.
Since API version 9, this API is supported in ArkTS widgets.| +| hueRotate | number \| string | '0deg' | Applies the hue rotation effect to the current component. The input parameter is a rotation angle.
Since API version 9, this API is supported in ArkTS widgets.| +| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | Applies the color blend effect to the current component. The input parameter is the blended color.
Since API version 9, this API is supported in ArkTS widgets.| + +## ShadowOptions + +Provides the shadow attributes, including the blur radius, color, and offset along the x-axis and y-axis. + +Since API version 9, this API is supported in ArkTS widgets. + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| radius | number \| [Resource](ts-types.md#resource) | Yes | Blur radius of the shadow. | +| color | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | No | Color of the shadow.
The default value is gray.| +| offsetX | number \| [Resource](ts-types.md#resource) | No | Offset of the shadow along the x-axis.
The default value is **0**. | +| offsetY | number \| [Resource](ts-types.md#resource) | No | Offset of the shadow along the y-axis.
The default value is **0**.| + +## ShadowStyle10+ + +| Name | Description | +| ------ | -------------------------------------- | +| OuterDefaultXS | Mini shadow.| +| OuterDefaultSM | Small shadow.| +| OuterDefaultMD | Medium shadow.| +| OuterDefaultLG | Large shadow.| +| OuterFloatingSM | Floating small shadow.| +| OuterFloatingMD | Floating medium shadow.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index 6fbaa35cdd66ca161b41999aedd1a2f06996f13d..76855375443264f0e2552db2b0df1fd339d8a53b 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -9,10 +9,10 @@ Layout constraints refer to constraints on the aspect ratio and display priority ## Attributes -| Name | Type | Description | -| --------------- | ------ | ---------------------------------------- | -| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. | -| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components.| +| Name | Type| Description | +| --------------- | -------- | ------------------------------------------------------------ | +| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height.
Since API version 9, this API is supported in ArkTS widgets.| +| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components.| ## Example 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 a603c54bc5f16e877420e80c1714ac16f70e2123..2c43828da9bc9d793b0fb75047e76cf862892712 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 @@ -12,12 +12,12 @@ The location attributes set the alignment mode, layout direction, and position o | Name| Type| Description| | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
Default value: **Alignment.Center**| -| direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**| -| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| -| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | -| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | -| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **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.| +| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
Default value: **Alignment.Center**
Since API version 9, this API is supported in ArkTS widgets.| +| direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**
Since API version 9, this API is supported in ArkTS widgets.| +| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Since API version 9, this API is supported in ArkTS widgets.| +| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
}
Since API version 9, this API is supported in ArkTS widgets.| +| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
}
Since API version 9, this API is supported in ArkTS widgets.| +| 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. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
This API is supported in ArkTS widgets.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md index 2ead12307d619826e4ae7ae26f29732df1302857..198d40461efcb6d586ef5ff5edb829be3f9ea224 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md @@ -10,9 +10,9 @@ You can set the opacity of a component. ## Attributes -| Name | Type | Description | -| ------- | ---------------------------------------- | ---------------------------------------- | -| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout. Default value: **1**
**NOTE**
A component inherits the opacity setting from its parent component and multiplies it by its own setting. For example, if the opacity of a component is 0.8 and that of its parent component is 0.1, then the actual opacity of the component is 0.1 x 0.8 = 0.8.| +| Name | Type | Description | +| ------- | ---------------------------------------------------- | ------------------------------------------------------------ | +| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout. Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A component inherits the opacity setting from its parent component and multiplies it by its own setting. For example, if the opacity of a component is 0.8 and that of its parent component is 0.1, then the actual opacity of the component is 0.1 x 0.8 = 0.8. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 4bb23b9f11f8f7ab4aa187fedaca3ab37716a461..412b3b5be90a52e110a7b45eef2069ccbf9c5a34 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -10,7 +10,7 @@ You can set overlay text for a component. | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | Overlay added to the component.
**value**: mask text.
**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.
If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.| +| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | Overlay added to the component.
**value**: mask text.
**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.
If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md index 5d3d604773dd94846f3f77957ce1bce86540e660..f0698f179b985dff0628d8d963b736ad51d7d16e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md @@ -11,10 +11,12 @@ You can set state-specific styles for components. | Style| Type| Description| | -------- | -------- | -------- | -| stateStyles | StateStyles | Styles of the component for different states.| +| stateStyles | StateStyles | Styles of the component for different states.
Since API version 9, this API is supported in ArkTS widgets.| ## StateStyles +Since API version 9, this API is supported in ArkTS widgets. + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | normal | ()=>void | No| Style of the component when being stateless.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 44ef15dc387f102ead0ba5b5031d0867b746c29e..3d1b5395fe965496db2ba6f310a8860eb9419c5c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -18,27 +18,28 @@ You can bind a popup to a component, specifying its content, interaction logic, | Name | Type | Mandatory | Description | | -------------------------| ------------------------------------------------| -----| ----------------------------------------- | -| message | string | Yes | Content of the popup message. | -| placementOnTop | boolean | No | Whether to display the popup above the component.
Default value: **false** | -| primaryButton | {
value: string,
action: () => void
} | No | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.| -| secondaryButton | {
value: string,
action: () => void
} | No | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.| +| message | string | Yes | Content of the popup message. | +| placementOnTop | boolean | No | Whether to display the popup above the component.
Default value: **false** | +| primaryButton | {
value: string,
action: () => void
} | No | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.| +| secondaryButton | {
value: string,
action: () => void
} | No | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.| | onStateChange | (event: { isVisible: boolean }) => void | No | Callback for the popup status change event.
**isVisible**: whether the popup is visible. | -| arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup.
When the arrow is at the top or bottom of the popup: The value 0 indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default.
When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default.
When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is 0, the arrow always points to the bound component. | +| arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup.
When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default.
When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default.
When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. | | showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow.
Default value: **false** | +| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No | Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.| ## CustomPopupOptions8+ | Name | Type | Mandatory | Description | | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | -| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.
Default value: **Placement.Bottom** | -| maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. | -| popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | -| enableArrow | boolean | No | Whether to display an arrow.
Since API version 9, if the position set for the popup is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** but the popup height is less than twice the arrow width (64 vp), the arrow will not be displayed.
Default value: **true**| -| autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.
Default value: **true** | -| onStateChange | (event: { isVisible: boolean }) => void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.| -| arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup.
When the arrow is at the top or bottom of the popup: The value 0 indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default.
When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default.
When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is 0, the arrow always points to the bound component. | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | +| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.
Default value: **Placement.Bottom** | +| popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | +| enableArrow | boolean | No | Whether to display an arrow.
Since API version 9, if the position set for the popup is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** but the popup height is less than twice the arrow width (64 vp), the arrow will not be displayed.
Default value: **true**| +| autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.
Default value: **true** | +| onStateChange | (event: { isVisible: boolean }) => void | No | Callback for the popup status change event.
**isVisible**: whether the popup is visible. | +| arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup.
When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default.
When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default.
When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. | | showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow.
Default value: **false** | +| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No| Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.| ## Example @@ -102,7 +103,7 @@ struct PopupExample { .bindPopup(this.customPopup, { builder: this.popupBuilder, placement: Placement.Top, - maskColor: 0x33000000, + mask: {color: 0x33000000}, popupColor: Color.Yellow, enableArrow: true, showInSubWindow: false, diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md index 3aaeb64451a672c5eb662fb4f79f166fd7afcab5..a62a7a53b11336ce58448233fe4b1765580b9265 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md @@ -12,8 +12,8 @@ Shape clipping changes the visible portion of a component through clipping or ma | Name | Type | Description | | -----| ------------------------------------------ | ------------------------------------ | -| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Clip mode. If the value is a shape, the component is clipped based on the specified shape. If the value is of the Boolean type, it specifies whether to clip the component based on the edge outline of the parent container.
Default value: **false**| -| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Mask of the specified shape to add to the component.| +| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Clip mode. If the value is a shape, the component is clipped based on the specified shape. If the value is of the Boolean type, it specifies whether to clip the component based on the edge outline of the parent container.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Mask of the specified shape to add to the component.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index fe7c40c76994b0088a21b6fb65867432a5fb7deb..63adc44dc9489b233c92d96176a7cf1d6e9eb520 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -10,15 +10,15 @@ The size attributes set the width, height, and margin of a component. ## Attributes -| Name | Type | Description | -| -------------- | ---------------------------------------- | ---------------------------------------- | -| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn. | -| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn. | -| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Size of the component. | -| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.
When the parameter is of the **Length** type, the four paddings take effect.
Default value: **0**
When **padding** is set to a percentage, the width of the parent container is used as the basic value.| -| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.| -| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
} | -| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.| +| Name | Type | Description | +| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.| +| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.| +| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Size of the component.
Since API version 9, this API is supported in ArkTS widgets.| +| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.
When the parameter is of the **Length** type, the four paddings take effect.
Default value: **0**
When **padding** is set to a percentage, the width of the parent container is used as the basic value.
Since API version 9, this API is supported in ArkTS widgets.| +| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.
Since API version 9, this API is supported in ArkTS widgets.| +| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
}
Since API version 9, this API is supported in ArkTS widgets.| +| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md index f78135e0ad613113d71fd10c3f054c74cf9cf68e..9cf189d9f4d2f607aeff6d361142fcbb8ff03557 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md @@ -11,12 +11,15 @@ You can set the touch target for components that support universal click events, ## Attributes -| Name | Type | Description | -| -------------- | --------------------------------------------- | ----------------------------------------- | -| responseRegion | Array<[Rectangle](#rectangle)> \| [Rectangle](#rectangle) | One or more touch targets, including their location and size.
The default touch target is the entire component. Default value:
{
x: 0,
y: 0,
width: '100%',
height: '100%'
} | +| Name | Type | Description | +| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| responseRegion | Array<[Rectangle](#rectangle)> \| [Rectangle](#rectangle) | One or more touch targets, including their location and size.
The default touch target is the entire component. Default value:
{
x: 0,
y: 0,
width: '100%',
height: '100%'
}
Since API version 9, this API is supported in ArkTS widgets.| ## Rectangle + +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Mandatory | Description | | ------ | ----------------------------- | -----| -------------------------------- | | x | [Length](ts-types.md#length) | No | X coordinate of the touch point relative to the upper left corner of the component.
Default value: **0vp**| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md index bf35ba4e5ee69b08d9621570b664af5ca6c0429e..3427774435b853cc8f3589c8dfc0e7c4c54572c2 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md @@ -11,9 +11,9 @@ Transformation attributes allow you to rotate, translate, scale, or transform a | Name | Type | Description | | --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | Rotation axis. A positive angle indicates a clockwise rotation, and a negative angle indicates a counterclockwise rotation. The default value is **0**. **centerX** and **centerY** are used to set the rotation center point.
Default value:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
} | -| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | Translation distance along the x-, y-, and z-axis. The translation direction is determined by the positive and negative values. The value cannot be a percentage.
Default value:
{
x: 0,
y: 0,
z: 0
} | -| scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | Scale ratio along the x-, y-, and z-axis. The default value is **1**. **centerX** and **centerY** are used to set the scale center point.
Default value:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
} | +| rotate | {
x?: number,
y?: number,
z?: number,
angle: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | Rotation axis. A positive angle indicates a clockwise rotation, and a negative angle indicates a counterclockwise rotation. The default value is **0**. **centerX** and **centerY** are used to set the rotation center point.
Default value:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
}
Since API version 9, this API is supported in ArkTS widgets.| +| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | Translation distance along the x-, y-, and z-axis. The translation direction is determined by the positive and negative values. The value cannot be a percentage.
Default value:
{
x: 0,
y: 0,
z: 0
}
Since API version 9, this API is supported in ArkTS widgets.| +| scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | Scale ratio along the x-, y-, and z-axis. The default value is **1**. **centerX** and **centerY** are used to set the scale center point.
Default value:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
}
Since API version 9, this API is supported in ArkTS widgets.| | transform | [Matrix4Transit](../apis/js-apis-matrix4.md) | Transformation matrix of the component. | diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md index 906b8fe2dff247520061d61a5f7275a32a023746..7bf991c7db0e1cd9c291dd740496890f06dc1af6 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md @@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible. | Name | Type | Description | | ---------- | ---------------------------- | ------------------------------------------ | -| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible** | +| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md index 24be504eef9a302db845b10a0f1e9f082d6d6efd..c4a0fa3b20338f824c93d29bf88e857c247c7f05 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md @@ -12,7 +12,7 @@ The **zIndex** attribute sets the z-order of a component in the stacking context | Name| Type| Description| | -------- | -------- | -------- | -| zIndex | number | Hierarchy of sibling components in a container. A larger value indicates a higher display level.| +| zIndex | number | Hierarchy of sibling components in a container. A larger value indicates a higher display level.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md index 226a6b6030f7050ddff13e6ccc37ddd3663afc4e..0936712b13880edcd098755dc388db885333dbc5 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md @@ -11,9 +11,12 @@ A click event is triggered when a component is clicked. | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | --------------------------------- | -| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about **event**, see **ClickEvent**.| +| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about **event**, see **ClickEvent**.
Since API version 9, this API is supported in ArkTS widgets.| ## ClickEvent + +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | ------------------- | ------------------------------------ | -------------------------------------------------------- | | screenX | number | X coordinate of the click relative to the upper left corner of the application window. | @@ -26,6 +29,8 @@ A click event is triggered when a component is clicked. ## EventTarget8+ +Since API version 9, this API is supported in ArkTS widgets. + | Name | Type | Description | | ---- | ------------------------- | ---------- | | area | [Area](ts-types.md#area8) | Area information of the target element.| 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 cf6afebdedc6782a19b98a25d9831f46515b4df2..47d797b263a133c740bcf5864b6347ed76af30b6 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 @@ -11,8 +11,8 @@ A drag event is triggered when a component is dragged. | Name | Bubbling Supported| Description | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | | onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) => [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo)) | No | Triggered when the component bound to the event is dragged for the first time.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
Return value: object being dragged, which is used for prompts displayed when the object is dragged.
A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.| -| onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item enters a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
This event is valid only when the **onDrop** event is listened to.| -| onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item moves in a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
This event is valid only when the **onDrop** event is listened to.| +| onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item enters a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
This event is valid only when a listener for the **onDrop** event is enabled.| +| onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item moves in a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
This event is valid only when a listener for the **onDrop** event is enabled.| | onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item leaves a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.
This event is valid only when a listener for the **onDrop** event is enabled.| | onDrop(event: (event?: [DragEvent](#dragevent), extraParams?: string) => void) | No | Triggered when the dragged item is dropped on a valid drop target.
- **event**: information about the drag event, including the coordinates of the item that is being dragged.
- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.| @@ -40,8 +40,8 @@ A drag event is triggered when a component is dragged. | Name | 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.| +| getX() | number | X-coordinate of the drag position relative to the upper left corner of the screen, in vp.| +| getY() | number | Y-coordinate of the drag position relative to the upper left corner of the screen, in vp.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md b/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md index 7b1db0758f125113d863399d75a7672db10c302a..1f46534fcf3dcd7822d802e20f778018a4b82060 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md @@ -9,10 +9,10 @@ The show/hide event is triggered when a component is mounted or unmounted from t ## Events -| Name | Bubbling Supported| Description | -| ------------------------------------------------ | -------- | -------------------------- | -| onAppear(event: () => void) | No | Triggered when the component is displayed.| -| onDisAppear(event: () => void) | No | Triggered when the component is hidden.| +| Name | Bubbling Supported| Description | +| ------------------------------------------------ | -------- | ------------------------------------------------------------ | +| onAppear(event: () => void) | No | Triggered when the component is displayed.
Since API version 9, this API is supported in ArkTS widgets.| +| onDisAppear(event: () => void) | No | Triggered when the component is hidden.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index 6de69bc7c9b039822badf8bdaf0027328c755e2e..6af20aafd50cecbcc2a3a3ad51553d542cf428ae 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -10,6 +10,7 @@ - [zlib Error Codes](errorcode-zlib.md) - Common Event and Notification - [Event Error Codes](errorcode-CommonEventService.md) + - [Notification Error Codes](errorcode-notification.md) - [DistributedNotificationService Error Codes](errorcode-DistributedNotificationService.md) - UI Page - [Animator Error Codes](errorcode-animator.md) @@ -19,20 +20,20 @@ - [colorSpaceManager Error Codes](errorcode-colorspace-manager.md) - [Display Error Codes](errorcode-display.md) - [Window Error Codes](errorcode-window.md) -- Media +- Multimedia - [Audio Error Codes](errorcode-audio.md) - [Media Error Codes](errorcode-media.md) - [AVSession Management Error Codes](errorcode-avsession.md) -- Resource Management +- Resource Manager - [I18N Error Codes](errorcode-i18n.md) - [Resource Manager Error Codes](errorcode-resource-manager.md) -- Resource Scheduling +- Background Task - [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) - [DeviceUsageStatistics Error Codes](errorcode-DeviceUsageStatistics.md) - [reminderAgentManager Error Codes](errorcode-reminderAgentManager.md) - [workScheduler Error Codes](errorcode-workScheduler.md) - Security - - [Ability Access Control Error Codes](errorcode-access-token.md) + - [Application Access Control Error Codes](errorcode-access-token.md) - [HUKS Error Codes](errorcode-huks.md) - [Crypto Framework Error Codes](errorcode-crypto-framework.md) - [Certificate Error Codes](errorcode-cert.md) @@ -45,12 +46,20 @@ - [Preferences Error Codes](errorcode-preferences.md) - File Management - [File Management Error Codes](errorcode-filemanagement.md) +- Telephony Service + - [Telephony Error Codes](errorcode-telephony.md) - Network Management - [Upload and Download Error Codes](errorcode-request.md) + - [HTTP Error Codes](errorcode-net-http.md) + - [Socket Error Codes](errorcode-net-socket.md) + - [Network Connection Management Error Codes](errorcode-net-connection.md) + - [Ethernet Connection Error Codes](errorcode-net-ethernet.md) + - [Network Sharing Error Codes](errorcode-net-sharing.md) + - [Policy Management Error Codes](errorcode-net-policy.md) - Connectivity + - [Wi-Fi Error Codes](errorcode-wifi.md) - [NFC Error Codes](errorcode-nfc.md) - [RPC Error Codes](errorcode-rpc.md) - - [Wi-Fi Error Codes](errorcode-wifi.md) - Basic Features - [Accessibility Error Codes](errorcode-accessibility.md) - [FaultLogger Error Codes](errorcode-faultlogger.md) @@ -78,9 +87,9 @@ - [System Parameter Error Codes](errorcode-system-parameterV9.md) - [USB Error Codes](errorcode-usb.md) - [Update Error Codes](errorcode-update.md) -- Customization Management +- Customization - [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md) -- Utils +- Language Base Class Library - [Utils Error Codes](errorcode-utils.md) - Test - [UiTest Error Codes](errorcode-uitest.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md b/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md index fc58fc8c6dcc0f1fd3351338bf38c9aa65f8e6b4..9b61d8e62ed722b1a3409d8d8ddcfe8c31962cc6 100644 --- a/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md +++ b/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md @@ -4,7 +4,7 @@ **Error Message** -Want action is null +The action field in the want parameter is null. **Description** @@ -22,7 +22,7 @@ Make sure the **Action** attribute in the **want** object is not null. **Error Message** -sandbox application can not send common event +A sandbox application cannot send common events. **Description** @@ -40,7 +40,7 @@ Check whether the application used to send a common event is a sandbox applicati **Error Message** -common event send frequency too high +Too many common events are send in a short period of time. **Description** @@ -58,7 +58,7 @@ Do not send common events too frequently. **Error Message** -not System services or System app +A third-party application cannot send system common events. **Description** @@ -76,7 +76,7 @@ Make sure the application to send system common events is a system application o **Error Message** -subscriber can not found +The subscriber is not found. **Description** @@ -94,7 +94,7 @@ Check whether the subscription has already been canceled. If the subscription ha **Error Message** -userId is invalid +Invalid userId. **Description** @@ -107,11 +107,12 @@ The user ID is different from the system user ID, or the application is not a sy **Solution** 1. Make sure the current user ID is the same as the system user ID. 2. Make sure the application is a system application or system service. + ## 1500007 Failed to Send a Request Through IPC **Error Message** -message send error +Failed to send the message. **Description** @@ -129,7 +130,7 @@ Do not set up connections frequently. Try again later. **Error Message** -CEMS error +Failed to read the data. **Description** @@ -147,7 +148,7 @@ Try again later. **Error Message** -system error +System error. **Description** diff --git a/en/application-dev/reference/errorcodes/errorcode-access-token.md b/en/application-dev/reference/errorcodes/errorcode-access-token.md index da0cb07f0e9947fbe6d86796a72466a926041bb4..b5280137e6fb1751020324750e5c7fa2b56c6127 100644 --- a/en/application-dev/reference/errorcodes/errorcode-access-token.md +++ b/en/application-dev/reference/errorcodes/errorcode-access-token.md @@ -1,4 +1,4 @@ -# Ability Access Control Error Codes +# Application Access Control Error Codes ## 12100001 Invalid Parameters diff --git a/en/application-dev/reference/errorcodes/errorcode-bundle.md b/en/application-dev/reference/errorcodes/errorcode-bundle.md index 54c246c0d0d23b2bc301910be46b407710e7bdfa..0787c1a76568ac0baf10306de38b8d97d6ada58e 100644 --- a/en/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/en/application-dev/reference/errorcodes/errorcode-bundle.md @@ -3,9 +3,11 @@ ## 17700001 Bundle Name Does Not Exist **Error Message** + The specified bundle name is not found. **Description** + When a query API is called, the bundle name passed in does not exist. **Possible Causes** @@ -20,9 +22,11 @@ When a query API is called, the bundle name passed in does not exist. ## 17700002 Module Name Does Not Exist **Error Message** + The specified module name is not found. **Description** + When a query API or an installation-free API is called, the module name passed in does not exist. **Possible Causes** @@ -36,9 +40,11 @@ When a query API or an installation-free API is called, the module name passed i ## 17700003 Ability Name Does Not Exist **Error Message** + The specified ability name is not found. **Description** + When a query API is called, the ability name passed in does not exist. **Possible Causes** @@ -52,9 +58,11 @@ When a query API is called, the ability name passed in does not exist. ## 17700004 User ID Does Not Exist **Error Message** + The specified user ID is not found. **Description** + When a user-related API is called, the user ID passed in does not exist. **Possible Causes** @@ -68,23 +76,29 @@ When a user-related API is called, the user ID passed in does not exist. ## 17700005 appId Is an Empty String **Error Message** + The specified app ID is empty string. **Description** + When an API of the **appControl** module is called, the application ID passed in does not exist. **Possible Causes** + **appId** is an empty string. **Solution** + Check whether **appId** is an empty string. ## 17700006 Permission Does Not Exist **Error Message** + The specified permission is not found. **Description** + When the **getPermissionDef** API of the **bundleManager** module is called, the permission passed in does not exist. **Possible Causes** @@ -98,9 +112,11 @@ When the **getPermissionDef** API of the **bundleManager** module is called, the ## 17700007 Incorrect Device ID **Error Message** + The specified device ID is not found. **Description** + When an API of the **distributedBundle** module is called, the device ID passed in does not exist. **Possible Causes** @@ -114,9 +130,11 @@ When an API of the **distributedBundle** module is called, the device ID passed ## 17700010 Bundle Installation Failure Due to File Parsing Failure **Error Message** + Failed to install the HAP because the HAP fails to be parsed. **Description** + When the **install** API of the **installer** module is called, the HAP passed in fails to be parsed. **Possible Causes** @@ -132,9 +150,11 @@ When the **install** API of the **installer** module is called, the HAP passed i ## 17700011 Bundle Installation Failure Due to Signature Verification Failure **Error Message** + Failed to install the HAP because the HAP signature fails to be verified. **Description** + Calling the **install** API of the **installer** module to install the bundle fails due to signature verification failure. **Possible Causes** @@ -146,16 +166,18 @@ Calling the **install** API of the **installer** module to install the bundle fa **Solution** 1. Check whether the HAP is signed. -2. Ensure that the signature certificate of the HAP is applied for from the application market. +2. Ensure that the signing certificate of the HAP is applied for from the application market. 3. Check whether the same certificate is used for signing multiple HAPs. 4. Check whether the certificate used for signing the upgrade HAP is the same as the certificate used for signing the installed HAP. ## 17700012 Bundle Installation Failure Due to Invalid File Path or Too Large File **Error Message** + Failed to install the HAP because the HAP path is invalid or the HAP is too large. **Description** + Calling the **install** API of the **installer** module to install the bundle fails because the HAP path is invalid or the HAP is too large. **Possible Causes** @@ -171,54 +193,87 @@ Calling the **install** API of the **installer** module to install the bundle fa ## 17700015 Bundle Installation Failure Due to Different Configuration Information of Multiple HAPs **Error Message** + Failed to install the HAPs because they have different configuration information. **Description** + Calling the **install** API of the **installer** module to install the bundle fails because the HAPs have different configuration information. **Possible Causes** + The fields under **app** in the configuration files of these HAPs are inconsistent. **Solution** + Check whether the fields under **app** are the same. ## 17700016 Bundle Installation Failure Due to Insufficient System Disk Space **Error Message** + Failed to install the HAP because of insufficient system disk space. **Description** + Calling the **install** API of the **installer** module to install the bundle fails due to insufficient system disk space. **Possible Causes** + The system disk space is insufficient. **Solution** + Check whether the system has sufficient disk space. ## 17700017 Bundle Installation Failure Because the Version to Install is Too Earlier **Error Message** + Failed to install the HAP since the version of the HAP to install is too early. **Description** + Calling the **install** API of the **installer** module to install the bundle fails because the version to install is earlier than the version in use. **Possible Causes** + The version number is earlier than the version in use. **Solution** + Ensure that the version of the bundle to install is not earlier than the version in use. +## 17700018 Bundle Installation Failure Because the Dependent Module Does Not Exist + +**Error Message** + +Failed to install because the dependent module does not exist. + +**Description** + +The dependent module does not exist during the HAP or HPS installation. + +**Possible Causes** + +The dependent module is not installed. + +**Solution** + +Install the dependent modules first. + ## 17700020 Failure to Uninstall Preinstalled Applications **Error Message** + The preinstalled app cannot be uninstalled. **Description** + Calling the **uninstall** API of the **installer** module to uninstall a preinstalled application fails. **Possible Causes** + 1. You might want to uninstall a non-preinstalled application but passed the bundle name of a preinstalled app. 2. The preinstalled application cannot be uninstalled. @@ -229,9 +284,11 @@ Calling the **uninstall** API of the **installer** module to uninstall a preinst ## 17700021 Invalid UID **Error Message** + The specified uid is invalid. **Description** + When the **getBundleNameByUid** API of the **bundleManager** module is called, the UID passed in is invalid. **Possible Causes** @@ -245,9 +302,11 @@ When the **getBundleNameByUid** API of the **bundleManager** module is called, t ## 17700022 Invalid Source File **Error Message** + The input source file is invalid. **Description** + When the **getBundleArchiveInfo** API of the **bundleManager** module is called, the HAP path passed in is invalid. **Possible Causes** @@ -261,26 +320,33 @@ When the **getBundleArchiveInfo** API of the **bundleManager** module is called, ## 17700023 Default Application Does Not Exist **Error Message** + The specified default app does not exist. **Description** + When the **getDefaultApplication** API of the **defaultAppManager** module is called, the specified default application does not exist. **Possible Causes** + No default application is set for the device. **Solution** + Check whether the default application is set on the device. ## 17700024 Configuration File Does Not Exist **Error Message** + Failed to get the profile because there is no profile in the HAP. **Description** + When an API for querying the profile is called, the configuration file does not exist **Possible Causes** + 1. The metadata name passed in the API does not exist in the configuration file. 2. The content of the configuration file is not in JSON format. @@ -291,9 +357,11 @@ When an API for querying the profile is called, the configuration file does not ## 17700025 Invalid Type **Error Message** + The specified type is invalid. **Description** + When an API of the **defaultAppManager** module is called, the type passed in is invalid. **Possible Causes** @@ -307,71 +375,237 @@ When an API of the **defaultAppManager** module is called, the type passed in is ## 17700026 Bundle Disabled **Error Message** + The specified bundle is disabled. **Description** + When an API for querying bundle information is called, the specified bundle is disabled. **Possible Causes** + The bundle on the device has been disabled and cannot be queried. **Solution** + Check whether the bundle on the device is disabled. ## 17700027 Distributed Service Is Not Started **Error Message** + The distributed service is not running. **Description** + When an API of the **distributedBundle** module is called, the distributed service is not started. **Possible Causes** + The device is not networked. **Solution** + Check whether the device is networked. + ## 17700028 Mismatch Between Ability and Type **Error Message** + The ability does not match the type. **Description** + When the **setDefaultApplication** API of the **defaultAppManager** module is called, the **ability** and **type** passed in do not match. **Possible Causes** + The ability and type are misspelled. **Solution** + Check whether the spellings of ability and type are correct. ## 17700029 Disabled Ability **Error Message** + The specified ability is disabled. **Description** + When an API for querying ability information is called, the specified ability is disabled. **Possible Causes** + The specified ability is disabled. **Solution** + Check whether the ability is disabled. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the information. ## 17700030 Failure in Clearing Cache Files **Error Message** + The specified bundle does not support clearing of cache files. **Description** + When the **cleanBundleCacheFiles** API of the **bundleManager** module is called, the specified bundle does not support cache file clearing. **Possible Causes** + The application is a system application and the **AllowAppDataNotCleared** field is configured in the signing certificate. **Solution** 1. Check whether the application is a system application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **isSystemApp** is **true**. -2. Check whether the **AllowAppDataNotCleared field** is configured for the application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **userDataClearable** is **true**. +2. Check whether the **AllowAppDataNotCleared** field is configured for the application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **userDataClearable** is **true**. + +## 17700031 HAP Installation Fails Due to Overlay Feature Verification Failure + +**Error Message** + +Failed to install the HAP because the overlay check of the HAP is failed. + +**Description** + +The target application and the to-be-installed application with the overlay feature are not preset applications, or the target application or target module is one with the overlay feature. - +**Possible Causes** +1. To use the overlay feature between applications, the following conditions must be met:
The application with the overlay feature must be a preset application. +2. The target application must be a preset application. +3. The target application cannot be an application with the overlay feature. +4. The target module cannot be a module with the overlay feature. + +**Solution** +1. Ensure that the application with the overlay feature is a preset application. +2. Ensure that the target application is a preset application. +3. Ensure that the target application is not an application with the overlay feature. +4. Ensure that the target module is not a module with the overlay feature. + +## 17700032 Application Does Not Contain a Module with the Overlay Feature + +**Error Message** + +The specified bundle does not contain any overlay module. + +**Description** + +An API is called to obtain the **overlayModuleInfo** object of another application, but that application does not contain a module with the overlay feature. + +**Possible Causes** + +The specified application does not contain a module with the overlay feature. + +**Solution** + +Check whether the application contains a module with the overlay feature. + +## 17700033 Module Is Not Configured with the Overlay Feature + +**Error Message** + +The specified module is not overlay module. + +**Description** + +An API is called to obtain the **overlayModuleInfo** object of a module, but the module is not configured with the overlay feature. + +**Possible Causes** + +The specified module is not a module with the overlay feature. + +**Solution** + +Check whether the module is configured with the overlay feature. + +## 17700034 Module Is Configured with the Overlay Feature + +**Error Message** + +The specified module is overlay module. + +**Description** + +An API is called to obtain the **overlayModuleInfo** object based on the target module name, but that module is configured with the overlay feature. + +**Possible Causes** + +The specified module is configured with the overlay feature. + +**Solution** + +Check whether the specified module is configured with the overlay feature. + +## 17700035 Application Contains Only Modules with the Overlay Feature + +**Error Message** + +The specified bundle is overlay bundle. + +**Description** + +An API is called to obtain the **overlayModuleInfo** object based on the target module name of another application, but that application contains only modules with the overlay feature. + +**Possible Causes** + +The specified application contains only modules with the overlay feature. + +**Solution** + +Check whether the application contains only modules with the overlay feature. + +## 17700036 Failure in Installing the Shared Library Because of No AllowAppShareLibrary Privilege + +**Error Message** + +Failed to install because without allow app shared bundle permission. + +**Description** + +The shared library is not configured with the **AllowAppShareLibrary** privilege, resulting in security and privacy risks. As a result, the installation fails. + +**Possible Causes** + +The shared library does not request the **AllowAppShareLibrary** privilege before being released. + +**Solution** + +Configure the **AllowAppShareLibrary** privilege for the shared library, re-sign the library, and release it. + +## 17700037 Failure in Uninstalling the Shared Library Due to Dependency + +**Error Message** + +The version of shared bundle is dependent on other applications. + +**Description** + +Other applications depend on the shared library, causing the uninstallation to fail. + +**Possible Causes** +1. The version specified during the uninstallation is the latest version of the shared library, and the shared library is depended on by other applications. +2. No version is not specified during the uninstallation, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications. + +**Solution** +1. Check whether the shared library to uninstall is depended on by other applications. +2. Check whether the version of the shared library to uninstall is the latest version of the shared library. + +## 17700038 Shared Library to Uninstall Does Not Exist + +**Error Message** + +The specified shared bundle does not exist. + +**Description** + +The shared library to uninstall does not exist. + +**Possible Causes** +1. The version specified during the uninstallation is different from the version of the shared library installed. +2. The shared library to uninstall is not installed. + +**Solution** +1. Check whether the shared library exists. +2. Check whether the version of the shared library is the same as that installed. diff --git a/en/application-dev/reference/errorcodes/errorcode-faultlogger.md b/en/application-dev/reference/errorcodes/errorcode-faultlogger.md index 9279760c6e3285d2a80d3785e8a91bb40859b3c3..303a61f8fc53975e9a71173970ed29a63f8a387b 100644 --- a/en/application-dev/reference/errorcodes/errorcode-faultlogger.md +++ b/en/application-dev/reference/errorcodes/errorcode-faultlogger.md @@ -4,11 +4,11 @@ **Error Message** -The service is not running or broken. +The service is not started or is faulty. **Description** -This error code is reported when the service is not started or is faulty. +This error code is reported when the service is not started or an unknown error occurs. **Possible Causes** diff --git a/en/application-dev/reference/errorcodes/errorcode-form.md b/en/application-dev/reference/errorcodes/errorcode-form.md index 232306b030f7ef912726a95548d4dc1efe1c8050..44184be85518557f141f05c49732fb3d2572399e 100644 --- a/en/application-dev/reference/errorcodes/errorcode-form.md +++ b/en/application-dev/reference/errorcodes/errorcode-form.md @@ -136,3 +136,39 @@ The widget does not belong to the application. 1. Check the ownership of the widget ID. 2. Upgrade the application permission to **SystemApp**. + +## 16501004 Ability Not Installed + +**Error Message** + +The ability is not installed. + +**Description** + +The specified ability is not installed. + +**Possible Causes** + +The specified ability is not installed. + +**Solution** + +Pass in valid **abilityName** and **bundleName**. + +## 16501005 Failed to Connect to FormRenderService + +**Error Message** + +Connect FormRenderService failed, please try again later. + +**Description** + +The FormRenderService fails to be connected. + +**Possible Causes** + +The service is busy. + +**Solution** + +Try again later. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-connection.md b/en/application-dev/reference/errorcodes/errorcode-net-connection.md new file mode 100644 index 0000000000000000000000000000000000000000..00e1eaaf78562f95549c4724e182c66878ea249b --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-connection.md @@ -0,0 +1,114 @@ +# Network Connection Management Error Codes + +## 2100001 Invalid Parameter Value + +**Error Message** + +Invalid parameter value. + +**Description** + +This error code is reported if the parameter value is invalid. + +**Cause** + +The input parameter value is not within the valid value range. + +**Procedure** + +Check whether the input parameter value is within the valid value range. + +## 2100002 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported if a service connection failure occurs. + +**Cause** + +The service is abnormal. + +**Procedure** + +Check whether system services are running properly. + +## 2100003 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. + +## 2101007 Callback Already Exists + +**Error Message** + +The same callback exists. + +**Description** + +This error code is reported if the same callback already exists. + +**Cause** + +The **callback** object has been registered for activating a network or listening to network status changes. + +**Procedure** + +1. Check whether the **callback** object has been registered. +2. If the **callback** object has been registered, use the registered **callback** object. + +## 2101008 Callback Not Exist + +**Error Message** + +The callback is not exists. + +**Description** + +This error code is reported if a **callback** object to be unregistered does not exist. + +**Cause** + +The **callback** object has not been registered for activating a network or listening to network status changes. + +**Procedure** + +Before unregistering a **callback** object, make sure that it has been registered for activating a network or listening to network status changes. + +## 2101022 Number of Requests Exceeding the Maximum + +**Error Message** + +The number of requests exceeded the maximum. + +**Description** + +This error code is reported if the number of network requests exceeds the maximum. + +**Cause** + +The number of requests for activating a network or listening to network status changes has reached the maximum value. + +**Procedure** + +Locate the fault based on the "Over the max request number" log record. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md b/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..b8a940de2a94863b309c4e6fd86600c39354a444 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md @@ -0,0 +1,116 @@ +# Ethernet Connection Error Codes + +## 2200001 Invalid Parameter Value + +**Error Message** + +Invalid parameter value. + +**Description** + +This error code is reported if the parameter value is invalid. + +**Cause** + +The input parameter value is not within the valid value range. + +**Procedure** + +Check whether the input parameter value is within the valid value range. + +## 2200002 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported if a service connection failure occurs. + +**Cause** + +The service is abnormal. + +**Procedure** + +Check whether system services are running properly. + +## 2200003 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. + +## 2201005 Device Information Not Exist + +**Error Message** + +The device information does not exist. + +**Description** + +This error code is reported if the device information does not exist. + +**Cause** + +The device to set or obtain does not exist. + +**Procedure** + + ```bash + > hdc shell ifconfig + ``` + Check whether the device, for example, **eth0** or **eth1**, exists. + +## 2201006 Device Not Connected + +**Error Message** + +Device disconnected. + +**Description** + +This error code is reported if the device is not connected. + +**Cause** + +The network interface card (NIC) is faulty. + +**Procedure** + +View the Ethernet service and netsys logs to check for the connection status information reported by the kernel. + +## 2201007 Failed to Write the User Configuration + +**Error Message** + +Failed to write the user configuration. + +**Description** + +This error code is reported if an error occurs while writing data to the user configuration file. + +**Cause** + +The system reports an error. + +**Procedure** + +A system internal error occurs. You are advised to locate the fault based on logs. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-http.md b/en/application-dev/reference/errorcodes/errorcode-net-http.md new file mode 100644 index 0000000000000000000000000000000000000000..bece9d1b26bdeae59cfd489432aa88f49bc7fe60 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-http.md @@ -0,0 +1,527 @@ +# HTTP Error Codes + +## 2300001 Protocol Not Supported + +**Error Message** + +Unsupported protocol. + +**Description** + +This error code is reported if the input protocol version is not supported by the server. + +**Cause** + +The input protocol version is not supported by the server. + +**Solution** + +Specify a protocol version supported by the server. + +## 2300003 Incorrect URL Format + +**Error Message** + +URL using bad/illegal format or missing URL. + +**Description** + +This error code is reported if the URL format is incorrect. + +**Cause** + +The format of the input URL is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300005 Failed to Resolve the Domain Name of the Proxy Server + +**Error Message** + +Couldn't resolve proxy name. + +**Description** + +This error code is reported if the domain name of the proxy server cannot be resolved. + +**Cause** + +This error code is reported if the URL of the proxy server is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300006 Failed to Resolve the Domain Name of the Host + +**Error Message** + +Couldn't resolve host name. + +**Description** + +This error code is reported if the domain name of the host cannot be resolved. + +**Cause** + +1. The input URL is incorrect. + +2. The network connection is abnormal. + +**Solution** + +1. Specify a URL of the correct format. + +2. Rectify network connection faults. + +## 2300007 Failed to Connect to the Server + +**Error Message** + +Couldn't connect to server. + +**Description** + +This error code is reported if the server connection failed. + +**Cause** + +The format of the input URL is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300008 Invalid Data Returned by the Server + +**Error Message** + +Weird server reply. + +**Description** + +This error code is reported if the data returned by the server is invalid. + +**Cause** + +The server encounters an error and returns data in non-HTTP format. + +**Solution** + +Check the server implementation. + +## 2300009 Access to Remote Resources Denied + +**Error Message** + +Access denied to remote resource. + +**Description** + +This error code is reported if the access to remote resources is denied by the server. + +**Cause** + +The access to the specified resource is denied by the server. + +**Solution** + +Check whether access to the requested resource is allowed. + +## 2300016 HTT2 Framing Layer Error + +**Error Message** + +Error in the HTTP2 framing layer. + +**Description** + +This error code is reported if an error occurs on the HTTP2 framing layer. + +**Cause** + +HTTP2 is not supported by the server. + +**Solution** + +Capture and analyze packets to check whether HTTP2 is supported by the server. + +## 2300018 Incomplete Data Returned by the Server + +**Error Message** + +Transferred a partial file. + +**Description** + +This error code is reported if data returned by the server is incomplete. + +**Cause** + +This problem is probable due to server implementation. + +**Solution** + +Check the server implementation. + +## 2300023 Failed to Write Received Data to a Disk or Application + +**Error Message** + +Failed writing received data to disk/application. + +**Description** + +This error code is reported if an error occurs while writing received data to the disk or application. + +**Cause** + +The application does not have the data write permission. + +**Solution** + +Check the permissions granted to the application. + +## 2300025 Failed to Upload Data + +**Error Message** + +Upload failed. + +**Description** + +This error code is reported if data upload fails. + +**Cause** + +The file is too large or the network is faulty. The server may reject the **STOR** command if FTP is used. + +**Solution** + +Check the file size and network status. + +## 2300026 Failed to Open or Read Local Data from a File or Application + +**Error Message** + +Failed to open/read local data from file/application. + +**Description** + +This error code is reported if an error occurs while opening or reading local data from a file or application. + +**Cause** + +The application does not have the data read permission. + +**Solution** + +Check the permissions granted to the application. + +## 2300027 Insufficient Memory + +**Error Message** + +Out of memory. + +**Description** + +This error code is reported if the memory is insufficient. + +**Cause** + +This error code is reported if the memory is insufficient. + +**Solution** + +Check the system memory. + +## 2300028 Operation Timeout + +**Error Message** + +Timeout was reached. + +**Description** + +This error code is reported if the operation times out. + +**Cause** + +The TCP connection or the read/write operation times out. + +**Solution** + +Rectify network faults. + +## 2300047 Maximum Redirections Reached + +**Error Message** + +Number of redirects hit maximum amount. + +**Description** + +This error code is reported if the number of redirections reaches the maximum. + +**Cause** + +Redirection is performed too frequently. + +**Solution** + +Check the server implementation. + +## 2300052 No Content Returned by the Server + +**Error Message** + +Server returned nothing (no headers, no data). + +**Description** + +This error code is reported if no content is returned by the server. + +**Cause** + +This problem is probable due to server implementation. + +**Solution** + +Check the server implementation. + +## 2300055 Failed to Send Network Data + +**Error Message** + +Failed sending data to the peer. + +**Description** + +This error code is reported if an error occurs while sending network data to the peer end. + +**Cause** + +This problem is probable due to a network fault. + +**Solution** + +Rectify network faults. + +## 2300056 Failed to Receive Network Data + +**Error Message** + +Failure when receiving data from the peer. + +**Description** + +This error code is reported if an error occurs while receiving network data from the peer end. + +**Cause** + +This problem is probable due to a network fault. + +**Solution** + +Rectify network faults. + +## 2300058 Local SSL Certificate Error + +**Error Message** + +Problem with the local SSL certificate. + +**Description** + +This error code is reported if the local SSL certificate is incorrect. + +**Cause** + +The format of the SSL certificate is incorrect. + +**Solution** + +Check the format of the SSL certificate. + +## 2300059 Failed to Use the Specified SSL Cipher Algorithm + +**Error Message** + +Couldn't use specified SSL cipher. + +**Description** + +This error code is reported if the specified SSL cipher algorithm cannot be used. + +**Cause** + +The system does not support the cipher algorithm negotiated between the client and server. + +**Solution** + +Capture and analyze packets to check whether the cipher algorithm is supported. + +## 2300060 Incorrect SSL Certificate or SSH Key of the Remote Server + +**Error Message** + +SSL peer certificate or SSH remote key was not OK. + +**Description** + +This error code is reported if the SSL certificate or SSH key of the remote server is incorrect. + +**Cause** + +It is probable that the server identity verification fails because the certificate has expired. + +**Solution** + +Check whether the certificate is valid. + +## 2300061 Unrecognized or Incorrect HTTP Encoding Format + +**Error Message** + +Unrecognized or bad HTTP Content or Transfer-Encoding. + +**Description** + +This error code is reported if the HTTP encoding format cannot be identified or is incorrect. + +**Cause** + +The HTTP encoding format is incorrect. + +**Solution** + +Check the server implementation. Currently, only gzip encoding is supported. + +## 2300063 Maximum File Size Exceeded + +**Error Message** + +Maximum file size exceeded. + +**Description** + +This error code is reported if the maximum file size is exceeded. + +**Cause** + +The downloaded file is too large. + +**Solution** + +Check the server implementation. + +## 2300070 Insufficient Server Disk Space + +**Error Message** + +Remote disk full or allocation exceeded. + +**Description** + +This error code is reported if the server disk space is insufficient. + +**Cause** + +The server disk is full. + +**Solution** + +Check the server disk space. + +## 2300073 Uploaded File Already Exists + +**Error Message** + +Remote file already exists. + +**Description** + +This error code is reported if the server finds that the uploaded file already exists. + +**Cause** + +The uploaded file already exists. + +**Solution** + +Check the server for files that already exist. + +## 2300077 No SSL CA Certificate or Access Permission + +**Error Message** + +Problem with the SSL CA cert (path? access rights?). + +**Description** + +This error code is reported if the SSL CA certificate does not exist or the access permission is not available. + +**Cause** + +The SSL CA certificate is not available or the access permission is not granted. + +**Solution** + +Check whether the SSL CA certificate exists or the access permission is granted. + +## 2300078 URL Requested File Not Found + +**Error Message** + +Remote file not found. + +**Description** + +This error code is reported if the file requested by the specified URL does not exist. + +**Cause** + +The file requested by the specified URL does not exist. + +**Solution** + +Check whether the file requested by the specified URL exists. + +## 2300094 Identity Verification Failed + +**Error Message** + +An authentication function returned an error. + +**Description** + +This error code is reported if identity verification fails. + +**Cause** + +The specified identity verification field does not match that on the server. + +**Solution** + +Check whether the specified identity verification field matches that on the server. + +## 2300999 Unknown Error + +**Error Message** + +Unknown Other Error. + +**Description** + +This error code is reported if an unknown error occurs. + +**Cause** + +An unknown error occurs. + +**Solution** + +Try again or contact technical support. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-policy.md b/en/application-dev/reference/errorcodes/errorcode-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..87e1ad36f03dc74003787c764521fca1de10e3b2 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-policy.md @@ -0,0 +1,59 @@ +# Policy Management Error Codes + +## 2100001 Invalid Parameter Value + +**Error Message** + +Invalid parameter value. + +**Description** + +Invalid parameter value + +**Cause** + +The input parameter value is not within the valid value range. + +**Procedure** + +Check whether the input parameter value is within the valid value range. + +## 2100002 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported if a service connection failure occurs. + +**Cause** + +The service is abnormal. + +**Procedure** + +Check whether system services are running properly. + +## 2100003 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-sharing.md b/en/application-dev/reference/errorcodes/errorcode-net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..5535d15e992c96d063746f89112be0d341f9a641 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-sharing.md @@ -0,0 +1,159 @@ +# Network Sharing Error Codes + +## 2200001 Invalid Parameter Value + +**Error Message** + +Invalid parameter value. + +**Description** + +This error code is reported if the parameter value is invalid. + +**Cause** + +The input parameter value is not within the valid value range. + +**Procedure** + +Check whether the input parameter value is within the valid value range. + +## 2200002 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported if a service connection failure occurs. + +**Cause** + +The service is abnormal. + +**Procedure** + +Check whether system services are running properly. + +## 2200003 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. + +## 2202004 Shared Iface Unavailable + +**Error Message** + +Try to share an unavailable iface. + +**Description** + +This error code is reported if an Iface is used. + +**Cause** + +The specified Iface does not exist or the Iface name is incorrect. + +**Procedure** + +1. Check whether the shared Iface is available. + + ```bash + > ifconfig -a + ``` + +2. Check whether the Iface name is correct. + +## 2202005 Wi-Fi Sharing Failure + +**Error Message** + +WiFi sharing failed. + +**Description** + +This error code is reported if Wi-Fi sharing fails. + +**Cause** + +No connected network is available and therefore the attempt to obtain the default network fails. + +**Procedure** + +Check whether the network connection is normal. + +## 2202006 Bluetooth Sharing Failure + +**Error Message** + +Bluetooth sharing failed. + +**Description** + +This error code is reported if Bluetooth sharing fails. + +**Cause** + +1. Bluetooth is disabled. + +2. No connected network is available and therefore the attempt to obtain the default network fails. + +**Procedure** + +1. Touch the Bluetooth icon to turn on Bluetooth mode. + +2. Check whether the network connection is normal. + +## 2202009 Failed to Enable Forwarding for Network Sharing + +**Error Message** + +Network share enable forwarding error. + +**Description** + +This error code is reported if an error occurs while enabling forwarding for network sharing. + +**Cause** + +The Iptables rule setting fails and therefore an error occurs while combining Iptables commands fails. + +**Procedure** + +Enable the debug log function, and check whether Iptables commands are correctly combined. + +## 2202011 Failed to Obtain the Network Sharing Configuration + +**Error Message** + +Cannot get network sharing configuration. + +**Description** + +This error code is reported if an error occurs while obtaining the network sharing configuration. + +**Cause** + +The configuration file directory is incorrect. + +**Procedure** + +Specify a correct configuration file directory. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-socket.md b/en/application-dev/reference/errorcodes/errorcode-net-socket.md new file mode 100644 index 0000000000000000000000000000000000000000..ebd15740b694e135c394b9459c06a7f09438fc8f --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-socket.md @@ -0,0 +1,351 @@ +# Socket Error Codes + +## 2301001 Operation Not Allowed + +**Error Message** + +Operation not permitted. + +**Description** + +This error code is reported if an operation is not allowed. + +**Cause** + +The operation is illegal. + +**Procedure** + +Check the operation procedure. + +## 2301002 File Not Exist + +**Error Message** + +No such file or directory. + +**Description** + +This error code is reported if the requested file does not exist. + +**Cause** + +The requested file does not exist. + +**Procedure** + +Check the file name or file path. + +## 2301003 Process Not Exist + +**Error Message** + +No such process. + +**Description** + +This error code is reported if a process does not exist. + +**Cause** + +The process does not exist. + +**Procedure** + +Check the process information. + +## 2301004 System Call Interrupted + +**Error Message** + +Interrupted system call. + +**Description** + +This error code is reported if the system call is interrupted. + +**Cause** + +The system call is interrupted. + +**Procedure** + +Rectify system call errors. + +**Description of TCP/UDP error codes:** +> Mapping format of other TCP/UDP Socket error codes: 2301000 + Linux kernel error code (errno). For details, see Linux kernel error codes. + +## 2300002 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. + +## 2303104 System Call Interrupted + +**Error Message** + +Interrupted system call. + +**Description** + +This error code is reported if the system call is interrupted. + +**Cause** + +Calling the **connect** function may result in a long blocking time. In such a case, the system generates an interrupt signal and returns an **EINTR** error. + +**Procedure** + +Call the **connect** function to try network connection again. + +## 2303109 Error File Number + +**Error Message** + +Bad file number. + +**Description** + +This error code is reported if an operation is performed on a locally closed socket. + +**Cause** + +The socket FD may be closed. + +**Procedure** + +Check whether the socket is closed unexpectedly. + +## 2303111 Requested Resource Temporarily Unavailable + +**Error Message** + +Resource temporarily unavailable try again. + +**Description** + +This error code is reported if the requested system resource is temporarily unavailable. + +**Cause** + +The system resources are in use. + +**Procedure** + +Try again later. + +## 2303188 Socket Operations on Non-Sockets + +**Error Message** + +Socket operation on non-socket. + +**Description** + +This error code is reported if a socket descriptor is not specified for the **socket** parameter. + +**Cause** + +A socket descriptor is not specified for the **socket** parameter. + +**Procedure** + +Check whether the descriptor is correctly obtained. + +## 2303191 Incorrect Socket Protocol Type + +**Error Message** + +Protocol wrong type for socket. + +**Description** + +This error code is reported if the type of the specified socket protocol is incorrect. + +**Cause** + +The **socket** function is called with an unsupported socket protocol type. +For example, the protocol type cannot be set to **SOCK_STREAM socket** for the the Internet UDP protocol. + +**Procedure** + +Check whether the socket protocol type is correct. + +## 2303198 Network Address Already In Use + +**Error Message** + +Address already in use. + +**Description** + +This error code is reported if a network address has been used. + +**Cause** + +The probable cause can be any of the following: The application attempts to bind a socket to an IP address/port that has been used for an existing socket. The socket is not properly closed. The socket is still being closed. + +**Procedure** + +Try another network address. + +## 2303199 Failed to Assign the Requested Address + +**Error Message** + +Cannot assign requested address. + +**Description** + +This error code is reported if the requested address is invalid in its context. + +**Cause** + +The remote address or port is invalid for the remote server. + +**Procedure** + +Check whether the address or port is correct. + +## 2303210 Connection Timeout + +**Error Message** + +Connection timed out. + +**Description** + +This error code is reported if the connection to the remote server cannot be set up for a long time. + +**Cause** + +It is probable that a server breakdown has occurred. + +**Procedure** + +Contact the peer end to rectify the fault. + +## 2303501 Null SSL + +**Error Message** + +SSL is null. + +**Description** + +This error code is reported if the SSL is null. + +**Cause** + +The returned error information is null when an internal function fails to be executed. + +**Procedure** + +Call the function again. + +## 2303502 TLS Reading Error + +**Error Message** + +Error in tls reading. + +**Description** + +This error code is reported if an error occurs while reading data on the TLS socket. + +**Cause** + +The underlying socket is blocked. + +**Procedure** + +Perform data receiving again. + +## 2303503 TLS Writing Error + +**Error Message** + +Error in tls writing. + +**Description** + +This error code is reported if an error occurs while writing data on the TLS socket. + +**Cause** + +When the send buffer is full, the underlying socket sends an **EWOUDLBLOCK** error, which means that the server does not read the data sent from the client. + +**Procedure** + +Rectify the fault on the server side. + +## 2303504 x509 Failed to Look Up the x509 Certificate + +**Error Message** + +Error looking up x509. + +**Description** + +An error occurred when verifying the x509 certificate. + +**Cause** + +The local certificate does not match the server certificate. + +**Procedure** + +Check whether the local CA matches the server certificate. + +## 2303505 TLS System Call Error + +**Error Message** + +Error occurred in the tls system call. + +**Description** + +This error code is reported if the TLS system call fails because of fatal I/O errors. + +**Cause** + +Network communication fails because of network faults. + +**Procedure** + +For details, see the Linux kernel error codes (errno). + +## 2303506 Failed to Close TLS Connections + +**Error Message** + +Error clearing tls connection. + +**Description** + +This error code is reported if the TLS/SSL connection to be closed has been disabled. + +**Cause** + +The TLS/SSL connection to be closed has been disabled. + +**Procedure** + +Initiate a new TLS/SSL connection. diff --git a/en/application-dev/reference/errorcodes/errorcode-telephony.md b/en/application-dev/reference/errorcodes/errorcode-telephony.md new file mode 100644 index 0000000000000000000000000000000000000000..f90efffed3589a42344d27fcbbf641872e295a96 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-telephony.md @@ -0,0 +1,172 @@ +# Telephony Error Codes + +## 8300001 Input Parameter Value Out of Range + +**Error Message** + +The input parameter value is out of range. + +**Description** + +This error code is reported if the value of the input parameter (for example, **slotId**) is not within the valid range. In this case, the API call will fail and the corresponding operation cannot be performed. + +**Cause** + +The input parameter value is invalid. + +**Solution** + +Enter a valid parameter value. + + + +## 8300002 Service Connection Error + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported if the attempt to connect to a service fails. + +**Cause** + +Service startup or IPC connection has failed. + +**Solution** + +Operation error. Try again later. + + + +## 8300003 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if an internal error has occurred. + +**Cause** + +The possible cause is that data read/write has failed because the network is abnormal. + +**Solution** + +Operation error. Try again later. + + +## 8300004 SIM Card Not Detected + +**Error Message** + +Do not have sim card. + +**Description** + +This error code is reported if no SIM card is detected. + +**Cause** + +No SIM card is inserted or the SIM card is not properly inserted. + +**Solution** + +Insert the SIM card or remove and insert the SIM card again. + + +## 8300999 Unknown Error + +**Error Message** + +Unknown error code. + +**Description** + +This error code is reported if an unknown error occurs. + +**Cause** + +An unexpected error occurs in the system. The possible cause is that error codes of the bottom layer are not within the processing range. + +**Solution** + +Operation error. Try again later. + + +## 8301001 SIM Card Not Activated + +**Error Message** + +SIM card is not activated. + +**Description** + +This error code is reported if the SIM card is not activated. + +**Cause** + +The SIM card is not activated. + +**Solution** + +Activate the SIM card. + + +## 8301002 Failed to Read or Update SIM Card Data + +**Error Message** + +SIM card operation error. + +**Description** + +This error code is reported if the attempt to read or update SIM card data has failed. + +**Cause** + +The SIM card does not support the operation, or the SIM card is damaged. + +**Solution** + +Contact the SIM card supplier, or replace the SIM card. + + +## 8301003 Incorrect SIM Card Configuration + +**Error Message** + +Operator config error. + +**Description** + +This error code is reported if the SIM card configuration is incorrect. + +**Cause** + +The configuration file delivered with the SIM card is not properly preconfigured. + +**Solution** + +Check whether the correct SIM card is inserted. + +## 8401001 Failed to Connect to the UT + +**Error Message** + +UT is not connected. + +**Description** + +This error code is reported if the UT is not connected. + +**Cause** + +The current carrier does not support sending of UT requests over a Wi-Fi network, but the mobile phone is connected to the Wi-Fi network. + +**Solution** + +Disconnect the Wi-Fi connection, and send a new UT request. diff --git a/en/application-dev/reference/native-lib/Readme-EN.md b/en/application-dev/reference/native-lib/Readme-EN.md index 4bcd443b78791b4f59eb16345bff7f4da93c30f0..9c12f39504aa2d6bc0e21dfb44b0b47aee13af4a 100644 --- a/en/application-dev/reference/native-lib/Readme-EN.md +++ b/en/application-dev/reference/native-lib/Readme-EN.md @@ -1,5 +1,4 @@ # Standard Libraries Supported by Native APIs - - [Node_API](third_party_napi/napi.md) - [libuv](third_party_libuv/libuv.md) - [Native Standard Libraries Supported by Openharmony](third_party_libc/musl.md) diff --git a/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md b/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md index 877a9da2d46e2e45391d24abfd81574658f8de76..ee2eb1bf6c1ab5473369e86287298349c54098eb 100644 --- a/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md +++ b/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md @@ -1,12 +1,12 @@ -# Native Api Symbols That May Invoke Failed Because of Permission Control +# Native API Symbols That May Fail to Be Invoked Due to Permission Control -| Symbols | Possiable Reason | +| Symbol| Possible Cause| | --- | --- | -| mlockall | usr namespace isolation or lack of CAP_IPC_LOCK privilege | -| swapon | usr namespace isolation | -| swapoff | usr namespace isolation | -| stime | usr namespace isolation or lack of CAP_SYS_TIME privilege | -| settimeofday | usr namespace isolation or lack of CAP_SYS_TIME privilege | -| adjtime | usr namespace isolation or lack of CAP_SYS_TIME privilege | -| clock_settime | usr namespace isolation or lack of CAP_SYS_TIME privilege | -| klogctl | usr namespace isolation or lack of CAP_SYS_ADMIN/CAP_SYSLOG privilege | \ No newline at end of file +| mlockall | User namespace isolation or lack of the CAP_IPC_LOCK privilege.| +| swapon | User namespace isolation. | +| swapoff | User namespace isolation. | +| stime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| +| settimeofday | User namespace isolation or lack of the CAP_SYS_TIME privilege.| +| adjtime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| +| clock_settime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| +| klogctl | User namespace isolation or lack of the CAP_SYS_ADMIN/CAP_SYSLOG privilege.| diff --git a/en/application-dev/reference/native-lib/third_party_libc/musl.md b/en/application-dev/reference/native-lib/third_party_libc/musl.md index 3f9b520e2d072da601530ef6cf86d7ec9e45d90e..360f9527a5a06466e9faf66137e29526c425b388 100644 --- a/en/application-dev/reference/native-lib/third_party_libc/musl.md +++ b/en/application-dev/reference/native-lib/third_party_libc/musl.md @@ -9,7 +9,7 @@ | C standard library | C11 standard library implemented by [libc, libm, and libdl](https://en.cppreference.com/w/c/header). | | C++ standard library ([libc++](https://libcxx.llvm.org/))| An implementation of the C++ standard library. | | Open Sound Library for Embedded Systems ([OpenSL ES](https://www.khronos.org/registry/OpenSL-ES/))| An embedded, cross-platform audio processing library.| -| [zlib](https://zlib.net/) | A general data compression library implemented in C/C++.| +| [zlib](https://zlib.net/) | A general data compression library implemented in C/C++.| | [EGL](https://www.khronos.org/egl/) | A standard software interface between rendering APIs and the underlying native window system.| | Open Graphics Library for Embedded Systems ([OpenGL ES](https://www.khronos.org/opengles/))| A cross-platform software interface for rendering 3D graphics on embedded and mobile systems.| @@ -17,11 +17,12 @@ The C standard library is a C11 standard library implemented by: -libc: provides thread-related functions and a majority of standard functions. +- libc: provides thread-related functions and a majority of standard functions. -libm: provides basic mathematical functions. +- libm: provides basic mathematical functions. + +- libdl: provides functions related to dynamic linking, such as **dlopen**. -libdl: provides functions related to dynamic linking, such as **dlopen**. **Version** @@ -35,7 +36,7 @@ C standard library includes a set of header files in accordance with standard C [Native API Symbols Not Exported](musl-peculiar-symbol.md) -[Native Api Symbols That May Invoke Failed Because of Permission Control](musl-permission-control-symbol.md) +[Native API Symbols That May Fail to Be Invoked Due to Permission Control](musl-permission-control-symbol.md) ## libc++ diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md index adede69fe1d7cd8c400d056d6588c9faab441513..a51200c0fdb7e0ac0ef1e68c7bb44ab7cea33a0b 100644 --- a/en/application-dev/reference/syscap-list.md +++ b/en/application-dev/reference/syscap-list.md @@ -1,6 +1,6 @@ # SystemCapability List -SystemCapability (SysCap in short) refers to a standalone feature in the operating system. +SysCap, short for System Capability, refers to a standalone feature in the OpenHarmony system. Before using an API for development, you are advised to familiarize yourself with [SysCap](syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. @@ -437,7 +437,7 @@ Basic media capabilities ## SystemCapability.Multimedia.Media.AudioPlayer -Media audio player capability +Audio player capability | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -461,7 +461,7 @@ Media video player capability ## SystemCapability.Multimedia.Media.VideoRecorder -Media video recorder capability +Video recorder capability | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -1125,7 +1125,7 @@ Environment-related interfaces ## SystemCapability.FileManagement.File.DistributedFile -Distributed file extension interfaces +Distributed file extension | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -1253,7 +1253,7 @@ Basic capabilities of cross-process data sharing ## SystemCapability.DistributedDataManager.DataShare.Consumer -Data conumser of cross-process data sharing +Data consumer of cross-process data sharing | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -1285,7 +1285,7 @@ Core basic functional modules for component runtime, including application initi ## SystemCapability.Ability.AbilityRuntime.FAModel -Feature ability (FA) model +Feature Ability (FA) model | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -1394,3 +1394,267 @@ VAID management service | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Security.CertificateManager + +Certificate management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Security.CryptoFramework + +Cryptographic framework – basic encryption and decryption capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.Core + +Core services of bundle management, including bundle information query, bundle installation, and bundle uninstallation + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.FreeInstall + +Installation-free features provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.Resource + +Icon and label acquisition provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.DefaultApp + +Default application management feature provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.Launcher + +Query feature provided by the bundle manager for Launcher + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.SandboxApp + +Sandbox application features provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.QuickFix + +Quick fix provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.AppControl + +Application control features provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Graphic.Graphic2D.ColorManager.Core + +Wide color gamut management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | Yes | No | No | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +Efficiency resource application + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AVPlayer + +Audio and 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.AVRecorder + +Audio and 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.Security.Cert + +Cryptographic framework – certificate capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Security.DataLossPrevention + +Data leakage prevention + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.Communication.NFC.Tag + +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.Communication.NFC.CardEmulation + +NFC card emulation service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.Multimedia.Image.ImageCreator + +Image creation capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Developtools.Syscap + +System capability encoding and decoding + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Communication.NetManager.Ethernet + +Ethernet connectivity + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetManager.NetSharing + +Network sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | Yes | No | No | + +## SystemCapability.Communication.NetManager.MDNS + +mDNS service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetManager.Vpn + +VPN + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | Yes | No | No | + +## SystemCapability.XTS.DeviceAttest + +Device attestation + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.XTS.DeviceAttestLite + +Lightweight device attestation + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.FileManagement.UserFileManager.Core + +Basic capabilities of public user file management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.UserFileManager.DistributedCore + +Distributed capabilities of public user file management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.UDMF.Core + +Distributed data management – core capabilities of the Unified Data Management Framework (UDMF) + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework.Overlay + +Overlay feature provided by the bundle manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Cloud.Push + +Push management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Multimedia.SystemSound.Core + +System sound management, covering ringtones, notifications, alarms, and more + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.QuickFix + +Quick fix + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index 65ee52d059ec38496df15214f669ed78f0252507..e1b0842824625ca049b80307e112a906f685b0bb 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -2,8 +2,8 @@ - Access Control - [Access Control (Permission) Overview](accesstoken-overview.md) - - [Permission Application Guide](accesstoken-guidelines.md) - - [API Access Permission Verification](permission-verify-guidelines.md) + - [Applying for Permissions](accesstoken-guidelines.md) + - [Verifying API Access Permissions](permission-verify-guidelines.md) - [Application Permission List](permission-list.md) - User Authentication - [User Authentication Overview](userauth-overview.md) diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index eab4a6b1197305ced0964a23ef44957e20a955c5..1a1f36e2a0d334d4c2564d66d4738cd5c83dab6e 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -1,4 +1,4 @@ -# Permission Application Guide +# Applying for Permissions ## When to Use @@ -13,24 +13,26 @@ This document describes the following operations: ## Declaring Permissions in the Configuration File -During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see [Application Models](../application-models/application-model-description.md). The application bundle and configuration file vary with the application model. +The permissions required by an application must be declared one by one in the configuration file of the project. Otherwise, the application cannot obtain the permissions. -> **NOTE**
The default APL of an application is **normal**. When an application of the **normal** APL needs a permission of the **system_basic** or **system_core** level, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-the-acl). +> **NOTE** +> +> If an application of the **normal** APL requires a permission of the **system_basic** or **system_core** level, you must also declare the permission in the [ACL](#declaring-the-acl). The following table describes the fields in the configuration file. | Field | Mandatory| Description | | --------- | -------- | ------------------------------------------------------------ | | name | Yes | Name of the permission. | -| reason | No | Reason for requesting the permission.
This field is mandatory when a user_grant permission is required.| -| usedScene | No | Application scenario of the permission.
This field is mandatory when a user_grant permission is required.| +| reason | No | Reason for requesting the permission.
This parameter is mandatory when a user_grant permission is required.| +| usedScene | No | Application scenario of the permission.
This parameter is mandatory when a user_grant permission is required.| | abilities | No | Abilities that require the permission. The value is an array.
**Applicable model**: stage| | ability | No | Abilities that require the permission. The value is an array.
**Applicable model**: FA| | when | No | Time when the permission is used.
Value:
- **inuse**: The permission applies only to a foreground application.
- **always**: The permission applies to both the foreground and background applications.| ### Stage Model -If your application is based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md). +If your application is developed based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md). ```json { @@ -64,7 +66,7 @@ If your application is based on the stage model, declare the required permission ### FA Model -If your application is based on the FA model, declare the required permissions in **config.json**. +If your application is developed based on the FA model, declare the required permissions in **config.json**. ```json { @@ -98,9 +100,9 @@ If your application is based on the FA model, declare the required permissions i ## Declaring the ACL -If an application of the **normal** APL requires permissions of the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL. +If an application of the **normal** APL requires permissions of the **system_basic** or **system_core** level, you must also declare the required permissions in the ACL. -For example, if an application needs to access audio files of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the required permissions to the **acls** field in the [HarmonyAppProvision configuration file](app-provision-structure.md). +For example, if an application needs to access audio clips of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the required permissions to the **acls** field in the [HarmonyAppProvision configuration file](app-provision-structure.md). ```json { @@ -116,82 +118,138 @@ For example, if an application needs to access audio files of a user and capture ## Requesting User Authorization -If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from the user. A permission verification is performed first to determine whether the current caller has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example. +The permissions for accessing user privacy information or using system abilities (for example, accessing Location or Calendar information or using the camera to take photos or record videos) request user authorization. Before an application that requires a **user_grant** permission is called, a verification is performed to check whether the user has granted the permission to the application. If the user has not granted the permission, a dialog box will be displayed to request user authorization. The following figure shows an example. +**Figure 1** Requesting authorization from a user ![](figures/permission-read_calendar.png) -> **NOTE**
Each time before an API protected by a user_grant permission is accessed, [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) will be called to request user authorization. After the permission is dynamically granted, the user may revoke the authorization. Therefore, the previously granted authorization status cannot be persistent. +> **NOTE** +> +> Each time before an API protected by a **user_grant** permission is called, **requestPermissionsFromUser()** will be called to request user authorization. After the permission is granted, the user may revoke the authorization in **Settings**. Therefore, the previously granted authorization status cannot be persistent. ### Stage Model -Example: Request the permission for an application to access calendar information. +Example: Apply for the permission for an application to access the Calendar. -1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file). +1. Declare the **ohos.permission.READ_CALENDAR** permission in the configuration file.
For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file). -2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the application has the permission. If yes, the target API can be called. +2. Check whether the user has granted the permission. + + Use [checkAccessToken()](../reference/apis/js-apis-abilityAccessCtrl.md#checkaccesstoken9) to check whether the user has granted the permission. If yes, the application can access the Calendar. Otherwise, request authorization from the user. + + ```ts + import bundleManager from '@ohos.bundle.bundleManager'; + import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; + + async function checkAccessToken(permission: Permissions): Promise { + let atManager = abilityAccessCtrl.createAtManager(); + let grantStatus: abilityAccessCtrl.GrantStatus; - Request user authorization in UIAbility. + // Obtain the access token ID of the application. + let tokenId: number; + try { + let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); + let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; + tokenId = appInfo.accessTokenId; + } catch (err) { + console.error(`getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`); + } + + // Check whether the user has granted the permission. + try { + grantStatus = await atManager.checkAccessToken(tokenId, permission); + } catch (err) { + console.error(`checkAccessToken failed, code is ${err.code}, message is ${err.message}`); + } + return grantStatus; + } + + async function checkPermissions(): Promise { + const permissions: Array = ['ohos.permission.READ_CALENDAR']; + let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]); + + if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + // If the user has granted the permission, the application can access the Calendar. + } else { + // Apply for the permission to access the Calendar. + } + } + ``` + +3. Request user authorization dynamically. + + Use [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to apply for permissions from the user when the application is running. A list of permissions, such as the permissions to access the Location, Calendar, camera, and microphone, can be passed in. The user can grant or deny the permissions. + + You can have [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) called in **onWindowStageCreate()** of the UIAbility to dynamically request user authorization, or request user authorization on the UI based on service requirements. + + Sample code for requesting user authorization using UIAbility: + ```typescript import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; + const permissions: Array = ['ohos.permission.READ_CALENDAR']; + export default class EntryAbility extends UIAbility { - // ... + // ... - onWindowStageCreate(windowStage: window.WindowStage) { - // Main window is created, set main page for this ability - let context = this.context; - let atManager = abilityAccessCtrl.createAtManager(); - // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. - const permissions: Array = ['ohos.permission.READ_CALENDAR']; - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.info(`[requestPermissions] data: ${JSON.stringify(data)}`); - let grantStatus: Array = data.authResults; - let length: number = grantStatus.length; - for (let i = 0; i < length; i++) { - if (grantStatus[i] !== 0) { - // The authorization fails. - return; - } - } - // The authorization is successful. - }).catch((err) => { - console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`); - }) - - // ... - } + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created. Set the main page for this ability. + let context = this.context; + let atManager = abilityAccessCtrl.createAtManager(); + // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. + + atManager.requestPermissionsFromUser(context, permissions).then((data) => { + let grantStatus: Array = data.authResults; + let length: number = grantStatus.length; + for (let i = 0; i < length; i++) { + if (grantStatus[i] === 0) { + // If the user has granted the permission, the application can access the Calendar. + } else { + // If the user has not granted the permission, display a message indicating that user authorization is required, and direct the user to the Settings page to set the permission. + return; + } + } + // The authorization is successful. + }).catch((err) => { + console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`); + }) + + // ... + } } ``` - - Request user authorization on the UI. + + Sample code for requesting user authorization on the UI: ```typescript import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import common from '@ohos.app.ability.common'; + const permissions: Array = ['ohos.permission.READ_CALENDAR']; + @Entry @Component struct Index { - reqPermissions() { + reqPermissionsFromUser(permissions: Array): void { let context = getContext(this) as common.UIAbilityContext; let atManager = abilityAccessCtrl.createAtManager(); // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. - const permissions: Array = ['ohos.permission.READ_CALENDAR']; atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.info(`[requestPermissions] data: ${JSON.stringify(data)}`); let grantStatus: Array = data.authResults; let length: number = grantStatus.length; for (let i = 0; i < length; i++) { - if (grantStatus[i] !== 0) { - // The authorization fails. + if (grantStatus[i] === 0) { + // If the user has granted the permission, the application can access the Calendar. + } else { + // If the user has not granted the permission, display a message indicating that user authorization is required, and direct the user to the Settings page to set the permission. return; } } // The authorization is successful. }).catch((err) => { - console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`); + console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`); }) } @@ -202,6 +260,27 @@ Example: Request the permission for an application to access calendar informatio } ``` +4. Perform subsequent operations based on the authorization result. + + After [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called, the application waits for the user authorization result. If the user has granted the permission, the application can access the Calendar. If the user has not granted the permission, a message will be displayed indicating that user authorization is required, and the user is directed to **Settings** to set the permission. + + ```ts + function openPermissionsInSystemSettings(): void { + let context = getContext(this) as common.UIAbilityContext; + let wantInfo = { + action: 'action.settings.app.info', + parameters: { + settingsParamBundleName: 'com.example.myapplication' // Open the Details page of the application. + } + } + context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) + } + ``` + ### FA Model Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization. @@ -223,10 +302,10 @@ reqPermissions() { } ``` ## Pre-Authorizing user_grant Permissions -By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission for camera applications, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the user_grant permissions in the file are granted. The **install_list_permissions.json** file contains the following fields: +By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, if you do not want the user authorization dialog box to display for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device, and is loaded when the device starts. When the application is installed, the **user_grant** permissions in the file are granted.
The **install_list_permissions.json** file contains the following fields: - **bundleName**: bundle name of the application. -- **app_signature**: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). +- **app_signature**: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson). - **permissions**: **name** specifies the name of the **user_grant** permission to pre-authorize. **userCancellable** specifies whether the user can revoke the pre-authorization. The value **true** means the user can revoke the pre-authorization; the value **false** means the opposite. > **NOTE**
This file is available only for preinstalled applications. diff --git a/en/application-dev/security/app-provision-structure.md b/en/application-dev/security/app-provision-structure.md index a772f024a4179af75e30dcf4f6bc0483ed0f86b0..c21fd0f533e72e41062a28d2c0d9f1ffdaabd9a1 100644 --- a/en/application-dev/security/app-provision-structure.md +++ b/en/application-dev/security/app-provision-structure.md @@ -1,22 +1,22 @@ # HarmonyAppProvision Configuration File -The **HarmonyAppProvision** configuration file (also called profile) is the file where you declare permission and signature information for your application. +The **HarmonyAppProvision** configuration file (also called profile) is a file where you declare permission and signature information for your application. -## Configuration File Internal Structure +## Configuration File Structure The **HarmonyAppProvision** file consists of several parts, which are described in the table below. -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- | -| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No | -| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No| -| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No| -| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes | No| -| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No| -| validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No | -| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No | -| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | Yes | -| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | Yes | -| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | Yes | -| app-privilege-capabilities | Privilege information required by the application bundle. For details, see the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). | String array| No | Yes | +| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes| No | +| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes| No| +| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes| No| +| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No| +| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes| No| +| validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes| No | +| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes| No | +| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No| Yes | +| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No| Yes | +| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No| Yes | +| app-privilege-capabilities | Privilege information required by the application bundle. For details, see the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). | String array| No| Yes | An example of the **HarmonyAppProvision** file is as follows: ```json @@ -53,47 +53,48 @@ An example of the **HarmonyAppProvision** file is as follows: ``` - ### Internal Structure of the validity Object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ---------- | ------------------------------- | ------- | ------- | --------- | -| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | -| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | +| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | +| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | ### Internal Structure of the bundle-info Object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +**NOTE**
The value of **bundle-name** in the **bundle-info** object in the HarmonyAppProvision file must be the same as the value of **bundleName** (in **config.js**/**module.json5**) of the signed application. To prevent a HarmonyAppProvision file from being used for signatures of different applications, the system checks whether the value of **bundleName** in the HAP signature is the same as that in the HAP configuration file during application installation. If they are different, the HAP cannot be installed. + +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | -------- | --------- | -| developer-id | Unique ID of the developer.| String | Yes | No | -| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | -| distribution-certificate | Information about the [release certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | -| bundle-name | Bundle name of the application.| String | Yes | No | -| apl | [Ability privilege level (APL)](accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | -| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (normal application). Only system applications are allowed to call system APIs. If a normal application calls a system API, the call cannot be successful or the application may run abnormally.| String | Yes | No | +| developer-id | Unique ID of the developer.| String | Yes| No | +| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | +| distribution-certificate | Information about the [release certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | +| bundle-name | Bundle name of the application.| String | Yes| No | +| apl | [Ability privilege level (APL)](accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes| No | +| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (normal application). Only system applications are allowed to call system APIs. If a normal application calls a system API, the call cannot be successful or the application may run abnormally.| String | Yes| No | ### Internal Structure of the acls Object The **acls** object contains the [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No | +| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No| No | ### Internal Structure of the permissions Object The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No | No | +| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No| No | ### Internal Structure of the debug-info Object The **debug-info** object contains debugging information of your application, mainly device management and control information. -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | -| device-ids | IDs of devices on which your application can be debugged.| String array | No | No | +| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No| No | +| device-ids | IDs of devices on which your application can be debugged.| String array | No| No | ## Modifying the HarmonyAppProvision Configuration File diff --git a/en/application-dev/security/permission-verify-guidelines.md b/en/application-dev/security/permission-verify-guidelines.md index e33d9e2021aeb0e29856253de897a92333530f29..c9eda82d1ee39427fae948d516214c31bbd36fcd 100644 --- a/en/application-dev/security/permission-verify-guidelines.md +++ b/en/application-dev/security/permission-verify-guidelines.md @@ -1,4 +1,4 @@ -# API Access Permission Verification +# Verifying API Access Permissions ## When to Use diff --git a/en/application-dev/task-management/Readme-EN.md b/en/application-dev/task-management/Readme-EN.md index 8f5c8d904521a8188079239092ffd5b88a58b955..b18e933695fa7e156440feafd5bfc7719b10b59e 100644 --- a/en/application-dev/task-management/Readme-EN.md +++ b/en/application-dev/task-management/Readme-EN.md @@ -1,4 +1,4 @@ -# Task Management +# Background Task Management - Background Task - [Background Task Management Overview](background-task-overview.md) @@ -8,6 +8,6 @@ - [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md) - [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md) -- Agent-Powered Scheduled Reminder +- Agent-Powered Reminder - [Agent-Powered Reminder Overview](reminder-agent-overview.md) - [Agent-Powered Reminder Development](reminder-agent-development.md) \ No newline at end of file diff --git a/en/application-dev/task-management/background-task-overview.md b/en/application-dev/task-management/background-task-overview.md index fcef6d4c6012386d5705efb59a247ac01425dd75..6f3252f0ad09e23b263590a51ba52749d357d526 100644 --- a/en/application-dev/task-management/background-task-overview.md +++ b/en/application-dev/task-management/background-task-overview.md @@ -41,7 +41,7 @@ Adhere to the following constraints and rules when using transient tasks: - **When to cancel**: The application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, the time frame allowed for the application to run in the background will be affected. -- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) +- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) ## Continuous Tasks Continuous tasks provide background running lifecycle support for services that can be directly perceived by users and need to run in the background. For example, if a service needs to play audio or continue with navigation and positioning in the background, which can be perceived by users, it can execute a continuous task in the respective background mode. @@ -58,7 +58,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas | audioRecording | Audio input | A recording task is running. | - | | location | Positioning and navigation | A positioning task is running. | - | | bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - | -| multiDeviceConnection | Distributed interconnection | A distributed task is running. | - | +| multiDeviceConnection | Multi-device application collaboration | A distributed task is running. | - | | wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications| | voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications| | taskKeeping | Computing task | A computing task is running | Effective only for specific devices | diff --git a/en/application-dev/task-management/continuous-task-dev-guide.md b/en/application-dev/task-management/continuous-task-dev-guide.md index b301ee707bf62ce6cf773be2b744d905e807da42..a5ba250e191fb5eaa9cb6cf1d7393b23f340ccb3 100644 --- a/en/application-dev/task-management/continuous-task-dev-guide.md +++ b/en/application-dev/task-management/continuous-task-dev-guide.md @@ -38,398 +38,398 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-a For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md). -1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file. - -``` -"module": { - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // Background mode - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission - } - ] -} -``` +1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **module.json5** file, and declare the corresponding background mode type for the ability that needs to use the task. + + ``` + "module": { + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] + } + ``` 2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details, see [UIAbility Component Overview](../application-models/uiability-overview.md). -```ts -import wantAgent from '@ohos.app.ability.wantAgent'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -@Entry -@Component -struct Index { - @State message: string = 'test' - // Use getContext to obtain the context of the Page ability. - private context: any = getContext(this) - - startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // Type of the operation to perform after the notification is clicked. - operationType: wantAgent.OperationType.START_ABILITY, - // Custom request code. - requestCode: 0, - // Execution attribute of the operation to perform after the notification is clicked. - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } - } - - stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - } - - build() { - Row() { - Column() { - Text("Index") - .fontSize(50) - .fontWeight(FontWeight.Bold) - - Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Request a continuous task by clicking a button. - this.startContinuousTask(); - - // Execute the continuous task logic, for example, music playback. - }) - - Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Stop the continuous task. - - // Cancel the continuous task by clicking a button. - this.stopContinuousTask(); - }) - } - .width('100%') - } - .height('100%') - } -} -``` + ```ts + import wantAgent from '@ohos.app.ability.wantAgent'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + + @Entry + @Component + struct Index { + @State message: string = 'test' + // Use getContext to obtain the context of the Page ability. + private context: any = getContext(this) + + startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", + } + ], + // Type of the operation to perform after the notification is clicked. + operationType: wantAgent.OperationType.START_ABILITY, + // Custom request code. + requestCode: 0, + // Execution attribute of the operation to perform after the notification is clicked. + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + build() { + Row() { + Column() { + Text("Index") + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // Request a continuous task by clicking a button. + this.startContinuousTask(); + + // Execute the continuous task logic, for example, music playback. + }) + + Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // Stop the continuous task. + + // Cancel the continuous task by clicking a button. + this.stopContinuousTask(); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` 3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-ability-call). -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -const MSG_SEND_METHOD: string = 'CallSendMsg'; - -let mContext = null; - -function startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // Type of the operation to perform after the notification is clicked. - operationType: wantAgent.OperationType.START_ABILITY, - // Custom request code. - requestCode: 0, - // Execution attribute of the operation to perform after the notification is clicked. - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -class MySequenceable { - num: number = 0; - str: String = ""; - - constructor(num, string) { - this.num = num; - this.str = string; - } - - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - return true; - } - - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - return true; - } -} - -function sendMsgCallback(data) { - console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new MySequenceable(0, "") - data.readSequenceable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - // You can execute different methods based on the str value in the sequenceable data sent by the caller. - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new MySequenceable(10, "Callee test"); -} - -export default class BgTaskAbility extends UIAbility { - onCreate(want, launchParam) { - console.info("[Demo] BgTaskAbility onCreate") - this.callee.on("test", sendMsgCallback); - - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - mContext = this.context; - } - - onDestroy() { - console.info("[Demo] BgTaskAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - console.info("[Demo] BgTaskAbility onWindowStageCreate") - - windowStage.loadContent("pages/index").then((data)=> { - console.info(`load content succeed with data ${JSON.stringify(data)}`) - }).catch((error)=>{ - console.error(`load content failed with error ${JSON.stringify(error)}`) - }) - } - - onWindowStageDestroy() { - console.info("[Demo] BgTaskAbility onWindowStageDestroy") - } - - onForeground() { - console.info("[Demo] BgTaskAbility onForeground") - } - - onBackground() { - console.info("[Demo] BgTaskAbility onBackground") - } -}; -``` + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + + const MSG_SEND_METHOD: string = 'CallSendMsg'; + + let mContext = null; + + function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", + } + ], + // Type of the operation to perform after the notification is clicked. + operationType: wantAgent.OperationType.START_ABILITY, + // Custom request code. + requestCode: 0, + // Execution attribute of the operation to perform after the notification is clicked. + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + class MyParcelable { + num: number = 0; + str: String = ""; + + constructor(num, string) { + this.num = num; + this.str = string; + } + + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + + function sendMsgCallback(data) { + console.info('BgTaskAbility funcCallBack is called ' + data) + let receivedData = new MyParcelable(0, "") + data.readParcelable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + // You can execute different methods based on the str value in the sequenceable data sent by the caller. + if (receivedData.str === 'start_bgtask') { + startContinuousTask() + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MyParcelable(10, "Callee test"); + } + + export default class BgTaskAbility extends UIAbility { + onCreate(want, launchParam) { + console.info("[Demo] BgTaskAbility onCreate") + this.callee.on("test", sendMsgCallback); + + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + mContext = this.context; + } + + onDestroy() { + console.info("[Demo] BgTaskAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + console.info("[Demo] BgTaskAbility onWindowStageCreate") + + windowStage.loadContent("pages/index").then((data)=> { + console.info(`load content succeed with data ${JSON.stringify(data)}`) + }).catch((error)=>{ + console.error(`load content failed with error ${JSON.stringify(error)}`) + }) + } + + onWindowStageDestroy() { + console.info("[Demo] BgTaskAbility onWindowStageDestroy") + } + + onForeground() { + console.info("[Demo] BgTaskAbility onForeground") + } + + onBackground() { + console.info("[Demo] BgTaskAbility onBackground") + } + }; + ``` ### Development in the FA Model For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.md). -If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. - -If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks. - -1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**. - -```json -"module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // Background mode - "type": "service" // The ability type is service. - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission - } - ] -} -``` - -2. Call the APIs for requesting and canceling a continuous task in the Service ability. - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; -import rpc from "@ohos.rpc"; - -function startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - // Type of the operation to perform after the notification is clicked. - operationType: wantAgent.OperationType.START_ABILITY, - // Custom request code. - requestCode: 0, - // Execution attribute of the operation to perform after the notification is clicked. - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -async function processAsyncJobs() { - // Execute the continuous task. - - // After the continuous task is complete, call the API to release resources. - stopContinuousTask(); -} - -let mMyStub; - -class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // The meaning of code is user-defined. - if (code === 1) { - // Receive the request code for requesting a continuous task. - startContinuousTask(); - // Execute the continuous task. - } else if (code === 2) { - // Receive the request code for canceling the continuous task. - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } -} - -export default { - onStart() { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // Call the API to start the task. - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, startId) { - console.info('ServiceAbility onCommand'); - } -}; -``` +If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the ServiceAbility. In the **onStart** callback of the ServiceAbility, call **startBackgroundRunning()** to declare that the ServiceAbility needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. + +If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the ServiceAbility. After obtaining the proxy of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks. + +1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **config.json** file, and declare the corresponding background mode type for the ServiceAbility that needs to use the task. + + ```json + "module": { + "package": "com.example.myapplication", + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + "type": "service" // The ability type is Service. + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] + } + ``` + +2. Call the APIs for requesting and canceling a continuous task in the ServiceAbility. + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent from '@ohos.app.ability.wantAgent'; + import rpc from "@ohos.rpc"; + + function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + // Type of the operation to perform after the notification is clicked. + operationType: wantAgent.OperationType.START_ABILITY, + // Custom request code. + requestCode: 0, + // Execution attribute of the operation to perform after the notification is clicked. + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + async function processAsyncJobs() { + // Execute the continuous task. + + // After the continuous task is complete, call the API to release resources. + stopContinuousTask(); + } + + let mMyStub; + + class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // The meaning of code is user-defined. + if (code === 1) { + // Receive the request code for requesting a continuous task. + startContinuousTask(); + // Execute the continuous task. + } else if (code === 2) { + // Receive the request code for canceling the continuous task. + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } + } + + export default { + onStart() { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // Call the API to start the task. + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, startId) { + console.info('ServiceAbility onCommand'); + } + }; + ``` \ No newline at end of file diff --git a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md index 3cdcd3ca61439fb42ff61184492332412fc77966..ec3399039a4d1aedfcce6b43c1b3187605b06dee 100644 --- a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md +++ b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -6,6 +6,9 @@ To further balance power consumption overhead of the system, privileged system a To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions. +## Constraints +Only system applications can request efficiency resources. + ## Available APIs **Table 1** Main APIs for efficiency resources @@ -22,48 +25,48 @@ To upgrade your application as a privileged application, you must evaluate your 2. When the task is complete, release the resources in time. You can choose whether to release some or all resources. -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -// Request efficiency resources. -let request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | - backgroundTaskManager.ResourceType.TIMER, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; - -let res; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// Release some efficiency resources. -request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, - isApply: false, - timeOut: 0, - reason: "reset", - isPersist: true, - isProcess: true, -}; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// Release all efficiency resources. -try { - backgroundTaskManager.resetAllEfficiencyResources(); -} catch (error) { - console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} -``` + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + + // Request efficiency resources. + let request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | + backgroundTaskManager.ResourceType.TIMER, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, + }; + + let res; + try { + res = backgroundTaskManager.applyEfficiencyResources(request); + console.info("the result of request is: " + res); + } catch (error) { + console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + + // Release some efficiency resources. + request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, + isApply: false, + timeOut: 0, + reason: "reset", + isPersist: true, + isProcess: true, + }; + try { + res = backgroundTaskManager.applyEfficiencyResources(request); + console.info("the result of request is: " + res); + } catch (error) { + console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + + // Release all efficiency resources. + try { + backgroundTaskManager.resetAllEfficiencyResources(); + } catch (error) { + console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + ``` \ No newline at end of file diff --git a/en/application-dev/task-management/work-scheduler-dev-guide.md b/en/application-dev/task-management/work-scheduler-dev-guide.md index 845423ee6fa93a39d5ac93cbd8856f0ec0e49c23..3e5bed0e6bb48c54eecef75694f2419b31600116 100644 --- a/en/application-dev/task-management/work-scheduler-dev-guide.md +++ b/en/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,7 +2,8 @@ ## When to Use -If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). +If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. +For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). ## Available APIs @@ -38,7 +39,7 @@ storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-work isRepeat| boolean |Whether the task is repeated. repeatCycleTime| number |Repeat interval. repeatCount | number|Number of repeat times. -parameters | {[key: string]: any} |Carried parameters. +parameters | {[key: string]: number | string | boolean} |Carried parameters. **Table 3** Work Scheduler callbacks @@ -64,135 +65,134 @@ onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops. 2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md). -```ts -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - -export default class MyExtension extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); - } - onWorkStop(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); - } -} -``` + ```ts + import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + + export default class MyExtension extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); + } + onWorkStop(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); + } + } + ``` 3. Start a Work Scheduler task. -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler'; -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.startWork(workInfo); - console.info('workschedulerLog startWork success'); -} catch (error) { - console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); -} -``` + let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } + } + try{ + workScheduler.startWork(workInfo); + console.info('workschedulerLog startWork success'); + } catch (error) { + console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); + } + ``` 4. Stop the Work Scheduler task. -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; - -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.stopWork(workInfo, false); - console.info('workschedulerLog stopWork success'); -} catch (error) { - console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler'; + + let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } + } + try{ + workScheduler.stopWork(workInfo, false); + console.info('workschedulerLog stopWork success'); + } catch (error) { + console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); + } + + ``` 5. Obtain a specified Work Scheduler task. -```ts -try{ - workScheduler.getWorkStatus(50, (error, res) => { - if (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); -} catch (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); -} -``` - + ```ts + try{ + workScheduler.getWorkStatus(50, (error, res) => { + if (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } else { + for (let item in res) { + console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); + } + } + }); + } catch (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } + ``` 6. Obtain all the Work Scheduler tasks. -```ts -try{ - workScheduler.obtainAllWorks((error, res) =>{ - if (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); -} catch (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + try{ + workScheduler.obtainAllWorks((error, res) =>{ + if (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); + } + }); + } catch (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } + ``` 7. Stop and clear all the Work Scheduler tasks. -```ts -try{ - workScheduler.stopAndClearWorks(); - console.info(`workschedulerLog stopAndClearWorks success`); -} catch (error) { - console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + try{ + workScheduler.stopAndClearWorks(); + console.info(`workschedulerLog stopAndClearWorks success`); + } catch (error) { + console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); + } + ``` 8. Check whether the last execution of a specified Work Scheduler task has timed out. -```ts -try{ - workScheduler.isLastWorkTimeOut(500, (error, res) =>{ - if (error) { - onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); -} catch (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); -} -``` - + ```ts + try{ + workScheduler.isLastWorkTimeOut(500, (error, res) =>{ + if (error) { + onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); + } + }); + } catch (error) { + console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } + ``` diff --git a/en/application-dev/telephony/telephony-call.md b/en/application-dev/telephony/telephony-call.md index bbef181efb128f47ee08fd84d5adb0fd1aa031b2..8fc44ed193a78137b73a29854e539494147b9bc2 100644 --- a/en/application-dev/telephony/telephony-call.md +++ b/en/application-dev/telephony/telephony-call.md @@ -43,7 +43,7 @@ The **observer** module provides the functions of subscribing to and unsubscribi ## How to Develop -### Making a Call by Using the **dial** API (Only for System Applications) +### Making a Call by Using the **dial** API (for System Applications Only) 1. Declare the required permission: **ohos.permission.PLACE_CALL**. This permission is of the **system\_basic** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. Then, declare the corresponding permission by following instructions in [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md index afd987b1607c3a489c7d686e848e61330e4f7a1f..09b8c42877602d230810e9c299cd6a1ab8d73c41 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -1,7 +1,7 @@ # UI Development - [ArkUI Overview](arkui-overview.md) -- UI Development with ArkTS-based Declarative Development Paradigm +- ArkTS-based Declarative Development Paradigm - [Overview](ui-ts-overview.md) - [Declarative UI Development Guidelines](ui-ts-developing-intro.md) - Declarative UI Development Examples @@ -27,7 +27,7 @@ - [Custom Component Lifecycle Callbacks](ui-ts-custom-component-lifecycle-callbacks.md) - [Web Component Development](ui-ts-components-web.md) - [Recommendations for Improving Performance](ui-ts-performance-improvement-recommendation.md) -- UI Development with JavaScript-compatible Web-like Development Paradigm +- JavaScript-compatible Web-like Development Paradigm - [Overview](ui-js-overview.md) - Framework Overview - [File Organization](js-framework-file.md) diff --git a/en/application-dev/ui/figures/en-us_image_0000001163531210.gif b/en/application-dev/ui/figures/en-us_image_0000001163531210.gif new file mode 100644 index 0000000000000000000000000000000000000000..47730f745cfd341cd6f11c9a3d4ce71d4b2795fb Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001163531210.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001189089950.gif b/en/application-dev/ui/figures/en-us_image_0000001189089950.gif new file mode 100644 index 0000000000000000000000000000000000000000..52e27cf794d93927462587c5fe202c1afb344b96 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001189089950.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001267887817.gif b/en/application-dev/ui/figures/en-us_image_0000001189249862.gif similarity index 100% rename from en/application-dev/ui/figures/en-us_image_0000001267887817.gif rename to en/application-dev/ui/figures/en-us_image_0000001189249862.gif diff --git a/en/application-dev/ui/figures/en-us_image_0000001223287656.gif b/en/application-dev/ui/figures/en-us_image_0000001223287656.gif deleted file mode 100644 index a6296483cbe2994e36e97d422588f3a9156b56eb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001223287656.gif and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001223287668.png b/en/application-dev/ui/figures/en-us_image_0000001223287668.png deleted file mode 100644 index 21d56ef14b92d136e304c4bae6ab8b1f447557bb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001223287668.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001234011019.gif b/en/application-dev/ui/figures/en-us_image_0000001234011019.gif new file mode 100644 index 0000000000000000000000000000000000000000..7dd539689ac7b81822c934bd3c515e1d4f002d85 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001234011019.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001234130975.png b/en/application-dev/ui/figures/en-us_image_0000001234130975.png new file mode 100644 index 0000000000000000000000000000000000000000..3c47ec4f057b8e4b616c43a9a74c5800ff6e1771 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001234130975.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001234289455.gif b/en/application-dev/ui/figures/en-us_image_0000001234289455.gif new file mode 100644 index 0000000000000000000000000000000000000000..7151147186f2a4f212a9b7fec79b95025be8e615 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001234289455.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001267607869.gif b/en/application-dev/ui/figures/en-us_image_0000001267607869.gif deleted file mode 100644 index eb0c760faaf917a6935af461e0094fd8e7b8e85b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001267607869.gif and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001267767837.gif b/en/application-dev/ui/figures/en-us_image_0000001267767837.gif deleted file mode 100644 index 24f00c9f1aa6ec431a355f5dd2d88b920607cd05..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001267767837.gif and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001267767841.gif b/en/application-dev/ui/figures/en-us_image_0000001267767841.gif deleted file mode 100644 index 8d5a07d1ff67011de5d0ec6bc0c2e552db9e5cd0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001267767841.gif and /dev/null differ diff --git a/en/application-dev/ui/ui-js-components-stepper.md b/en/application-dev/ui/ui-js-components-stepper.md index 2ac27eb69a7ba2cbe248994daf2e46ec06f795e4..9e4c0fc869b27d64dc12ca27171eff333ec78e47 100644 --- a/en/application-dev/ui/ui-js-components-stepper.md +++ b/en/application-dev/ui/ui-js-components-stepper.md @@ -43,7 +43,7 @@ text{ } ``` -![en-us_image_0000001223287656](figures/en-us_image_0000001223287656.gif) +![en-us_image_0000001234289455](figures/en-us_image_0000001234289455.gif) ## Setting the Index @@ -82,7 +82,7 @@ text{ } ``` -![en-us_image_0000001267767837](figures/en-us_image_0000001267767837.gif) +![en-us_image_0000001234011019](figures/en-us_image_0000001234011019.gif) Set the **label** attribute to customize the label for the **\**. @@ -143,7 +143,7 @@ export default { } ``` -![en-us_image_0000001267767841](figures/en-us_image_0000001267767841.gif) +![en-us_image_0000001163531210](figures/en-us_image_0000001163531210.gif) ## Setting Styles @@ -187,7 +187,7 @@ text{ } ``` -![en-us_image_0000001223287668](figures/en-us_image_0000001223287668.png) +![en-us_image_0000001234130975](figures/en-us_image_0000001234130975.png) ## Adding Events @@ -290,7 +290,7 @@ export default { } ``` -![en-us_image_0000001267607869](figures/en-us_image_0000001267607869.gif) +![en-us_image_0000001189089950](figures/en-us_image_0000001189089950.gif) ## Example Scenario @@ -404,4 +404,4 @@ export default { } ``` -![en-us_image_0000001267887817](figures/en-us_image_0000001267887817.gif) +![en-us_image_0000001189249862](figures/en-us_image_0000001189249862.gif) diff --git a/en/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md b/en/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md index 22e3a6d598b8fdd0aa986c15c0671e191be2da7a..1ac564f253d1c361d6aeb00ffacbe37716f921b1 100644 --- a/en/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md +++ b/en/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md @@ -15,12 +15,16 @@ aboutToAppear?(): void Invoked after a new instance of the custom component is created and before its **build** function is executed. You can change state variables in the **aboutToAppear** function. The change will take effect when you execute the **build** function next time. +Since API version 9, this API is supported in ArkTS widgets. + ## aboutToDisappear aboutToDisappear?(): void Invoked before the destructor of the custom component is consumed. Do not change state variables in the **aboutToDisappear** function as doing this can cause unexpected errors. For example, the modification of the **@Link** decorated variable may cause unstable application running. +Since API version 9, this API is supported in ArkTS widgets. + **Example 1:** ```ts @@ -122,6 +126,8 @@ onLayout?(children: Array\, constraint: ConstraintSizeOptions): vo Invoked when the custom component lays out its child components. Through this callback the component receives its child component layout information and size constraint from the framework. The state variable cannot be changed in the **onLayout** function. +This API is supported in ArkTS widgets. + **Parameters** | Name | Type | Description | @@ -135,6 +141,8 @@ onMeasure?(children: Array\, constraint: ConstraintSizeOptions): v Invoked when the custom component needs to determine its size. Through this callback the component receives its child component layout information and size constraint from the framework. The state variable cannot be changed in the onMeasure function. +This API is supported in ArkTS widgets. + **Parameters** | Name | Type | Description | @@ -146,6 +154,8 @@ Invoked when the custom component needs to determine its size. Through this call Provides the child component layout information. +This API is supported in ArkTS widgets. + | Name | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------- | | name | string | Name of the child component. | @@ -160,6 +170,8 @@ Provides the child component layout information. Provides the border information of the child component. +This API is supported in ArkTS widgets. + | Name | Type | Description | | ----------- | ---------------------------------------------------------- | ---------------------------------------------- | | borderWidth | [EdgeWidths](../reference/arkui-ts/ts-types.md#edgewidths) | Edge widths in different directions of the child component.| @@ -170,6 +182,8 @@ Provides the border information of the child component. Provides the layout information of the child component. +This API is supported in ArkTS widgets. + | Name | Type | Description | | ---------- | -------------------------------------------------------------------------------- | ---------------- | | position | [Position](../reference/arkui-ts/ts-types.md#position) | Position coordinates of the child component.| diff --git a/en/application-dev/ui/ui-ts-layout-grid-container-new.md b/en/application-dev/ui/ui-ts-layout-grid-container-new.md index f51288b2a77901abf6620a6bcc8f0499fb647289..be3e2178b464ee8f5b711ba25dd0863c9ad88a10 100644 --- a/en/application-dev/ui/ui-ts-layout-grid-container-new.md +++ b/en/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -30,8 +30,8 @@ By default, the grid system provides four breakpoints: xs, sm, md, and lg. | Breakpoint | Value Range (vp)| | --------| ------ | | xs | [0, 320) | -| sm | [320, 520) | -| md | [520, 840) | +| sm | [320, 600) | +| md | [600, 840) | | lg | [840, +∞) | In the **\** component, you can use **breakpoints** to customize the value range of breakpoints. A maximum of six breakpoints are supported. @@ -55,10 +55,10 @@ In addition to the four default breakpoints, you can also enable the xl and xxl Enables three breakpoints: xs, sm, and md. If the value is less than 100 vp, the breakpoint is xs. If the value is 100–200 vp, the breakpoint is sm. If the value is greater than 200 vp, the breakpoint is md. ```ts - breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]} + breakpoints: {value: ["320vp", "600vp", "840vp", "1080vp"]} ``` - Enables five breakpoints: xs, sm, md, lg, and xl. If the value is less than 320 vp, the breakpoint is xs. If the value is 320–520 vp, the breakpoint is sm. If the value is 520–840 vp, the breakpoint is md. If the value is 840–1080vp, the breakpoint is lg. If the value is greater than 1080 vp, the breakpoint is xl. + Enables five breakpoints: xs, sm, md, lg, and xl. If the value is less than 320 vp, the breakpoint is xs. If the value is 320–600 vp, the breakpoint is sm. If the value is 600–840 vp, the breakpoint is md. If the value is 840–1080vp, the breakpoint is lg. If the value is greater than 1080 vp, the breakpoint is xl. - The grid system implements breakpoints by listening for the changes in the window or container size, and sets the breakpoint references through **reference**. Considering that the application may be displayed in non-full-screen mode, design the breakpoints with the application window width as the reference. diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 2364014ef49503250393370882bcb6ebae8d4a48..40a5c8bd53fb06344a61e98a421706cf9dd89038 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -12,7 +12,6 @@ - Application Package Structure - [Application Package Structure in Stage Model](quick-start/application-package-structure-stage.md) - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) - - [HAR File Structure](quick-start/har-structure.md) - Multi-HAP Mechanism - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) - [Multi-HAP Build View](quick-start/multi-hap-build-view.md) @@ -60,8 +59,11 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](application-models/extensionability-overview.md) - [ServiceExtensionAbility](application-models/serviceextensionability.md) - - [DataShareExtensionAbility](application-models/datashareextensionability.md) + - [DataShareExtensionAbility (for System Applications Only)](application-models/datashareextensionability.md) - [FormExtensionAbility (Widget)](application-models/widget-development-stage.md) + - [AccessibilityExtensionAbility](application-models/accessibilityextensionability.md) + - [InputMethodExtensionAbility](application-models/inputmethodextentionability.md) + - [WindowExtensionAbility](application-models/windowextensionability.md) - [AbilityStage Component Container](application-models/abilitystage.md) - [Context](application-models/application-context-stage.md) - Want @@ -74,8 +76,8 @@ - [Component Startup Rules (Stage Model)](application-models/component-startup-rules.md) - Inter-Device Application Component Interaction (Continuation) - [Continuation Overview](application-models/inter-device-interaction-hop-overview.md) - - [Cross-Device Migration](application-models/hop-cross-device-migration.md) - - [Multi-device Collaboration](application-models/hop-multi-device-collaboration.md) + - [Cross-Device Migration (for System Applications Only)](application-models/hop-cross-device-migration.md) + - [Multi-device Collaboration (for System Applications Only)](application-models/hop-multi-device-collaboration.md) - IPC - [Process Model](application-models/process-model-stage.md) - Common Events @@ -104,7 +106,7 @@ - [Creating a PageAbility](application-models/create-pageability.md) - [Starting a Local PageAbility](application-models/start-local-pageability.md) - [Stopping a PageAbility](application-models/stop-pageability.md) - - [Starting a Remote PageAbility](application-models/start-remote-pageability.md) + - [Starting a Remote PageAbility (for System Applications Only)](application-models/start-remote-pageability.md) - [Starting a Specified Page](application-models/start-page.md) - [Window Properties](application-models/window-properties.md) - [Requesting Permissions](application-models/request-permissions.md) @@ -270,7 +272,7 @@ - [Custom Components](ui/ui-js-custom-components.md) - Notification - [Notification Overview](notification/notification-overview.md) - - [Notification Subscription (Open Only to System Applications)](notification/notification-subscription.md) + - [Notification Subscription (for System Applications Only)](notification/notification-subscription.md) - [Enabling Notification](notification/notification-enable.md) - Publishing a Notification - [Publishing a Basic Notification](notification/text-notification.md) @@ -297,10 +299,10 @@ - [Audio Routing and Device Management Development](media/audio-routing-manager.md) - [AVPlayer Development (Recommended)](media/avplayer-playback.md) - [AVRecorder Development (Recommended)](media/avrecorder.md) - - [Audio Playback Development](media/audio-playback.md) - - [Audio Recording Development](media/audio-recorder.md) - - [Video Playback Development](media/video-playback.md) - - [Video Recording Development](media/video-recorder.md) + - [Audio Playback Development (To Be Deprecated Soon)](media/audio-playback.md) + - [Audio Recording Development (To Be Deprecated Soon)](media/audio-recorder.md) + - [Video Playback Development (To Be Deprecated Soon)](media/video-playback.md) + - [Video Recording Development (To Be Deprecated Soon)](media/video-recorder.md) - AVSession - [AVSession Overview](media/avsession-overview.md) - [AVSession Development](media/avsession-guidelines.md) @@ -337,11 +339,15 @@ - [HTTP Data Request](connectivity/http-request.md) - [WebSocket Connection](connectivity/websocket-connection.md) - [Socket Connection](connectivity/socket-connection.md) + - [Network Policy Management](connectivity/net-policy-management.md) + - [Network Sharing](connectivity/net-sharing.md) + - [Ethernet Connection](connectivity/net-ethernet.md) + - [Network Connection Management](connectivity/net-connection-manager.md) - IPC & RPC - [IPC & RPC Overview](connectivity/ipc-rpc-overview.md) - [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md) - [Subscribing to State Changes of a Remote Object](connectivity/subscribe-remote-state.md) - - Telephony + - Telephony Service - [Telephony Service Overview](telephony/telephony-overview.md) - [Call Service Development](telephony/telephony-call.md) - [SMS Service Development](telephony/telephony-sms.md) @@ -370,8 +376,8 @@ - File Access Framework - [File Access Framework Overview](file-management/file-access-framework-overview.md) - [FilePicker Guide](file-management/filepicker-guidelines.md) - - Task Management - - Background Task Management + - Background Task Management + - Background Task - [Background Task Management Overview](task-management/background-task-overview.md) - [Transient Task Development](task-management/transient-task-dev-guide.md) - [Continuous Task Development](task-management/continuous-task-dev-guide.md) @@ -381,7 +387,7 @@ - Agent-Powered Reminder - [Agent-Powered Reminder Overview](task-management/reminder-agent-overview.md) - [Agent-Powered Reminder Development](task-management/reminder-agent-development.md) - - Device + - Device Management - USB Service - [USB Service Overview](device/usb-overview.md) - [USB Service Development](device/usb-guidelines.md) @@ -399,6 +405,8 @@ - Update Service - [Sample Server Overview](device/sample-server-overview.md) - [Sample Server Development](device/sample-server-guidelines.md) + - Stationary + - [Stationary Development](device/stationary-guidelines.md) - Device Usage Statistics - [Device Usage Statistics Overview](device-usage-statistics/device-usage-statistics-overview.md) - [Device Usage Statistics Development](device-usage-statistics/device-usage-statistics-use-guide.md) @@ -508,6 +516,9 @@ - [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md) - [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) + - [Menu](reference/arkui-ts/ts-basic-components-menu.md) + - [MenuItem](reference/arkui-ts/ts-basic-components-menuitem.md) + - [MenuItemGroup](reference/arkui-ts/ts-basic-components-menuitemgroup.md) - [Navigation](reference/arkui-ts/ts-basic-components-navigation.md) - [NavRouter](reference/arkui-ts/ts-basic-components-navrouter.md) - [NavDestination](reference/arkui-ts/ts-basic-components-navdestination.md) @@ -868,6 +879,20 @@ - [@ohos.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md) - application - [EventHub](reference/apis/js-apis-inner-application-eventHub.md) + - commonEvent + - [CommonEventData](reference/apis/js-apis-inner-commonEvent-commonEventData.md) + - [CommonEventPublishData](reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md) + - [CommonEventSubscriber](reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md) + - [CommonEventSubscribeInfo](reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md) + - notification + - [NotificationActionButton](reference/apis/js-apis-inner-notification-notificationActionButton.md) + - [NotificationCommonDef](reference/apis/js-apis-inner-notification-notificationCommonDef.md) + - [NotificationContent](reference/apis/js-apis-inner-notification-notificationContent.md) + - [NotificationFlags](reference/apis/js-apis-inner-notification-notificationFlags.md) + - [NotificationRequest](reference/apis/js-apis-inner-notification-notificationRequest.md) + - [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md) + - [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.md) + - [NotificationUserInput](reference/apis/js-apis-inner-notification-notificationUserInput.md) - Bundle Management - [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md) @@ -882,6 +907,7 @@ - [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.md) - [applicationInfo](reference/apis/js-apis-bundleManager-applicationInfo.md) - [bundleInfo](reference/apis/js-apis-bundleManager-bundleInfo.md) + - [BundlePackInfo](reference/apis/js-apis-bundleManager-BundlePackInfo.md) - [dispatchInfo](reference/apis/js-apis-bundleManager-dispatchInfo.md) - [elementName](reference/apis/js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](reference/apis/js-apis-bundleManager-extensionAbilityInfo.md) @@ -910,17 +936,17 @@ - webgl - [WebGL](reference/apis/js-apis-webgl.md) - [WebGL2](reference/apis/js-apis-webgl2.md) - - Media + - Multimedia - [@ohos.multimedia.audio (Audio Management)](reference/apis/js-apis-audio.md) - [@ohos.multimedia.avsession (AVSession Management)](reference/apis/js-apis-avsession.md) - [@ohos.multimedia.camera (Camera Management)](reference/apis/js-apis-camera.md) - [@ohos.multimedia.image (Image Processing)](reference/apis/js-apis-image.md) - [@ohos.multimedia.media (Media)](reference/apis/js-apis-media.md) - - Resource Management + - Resource Manager - [@ohos.i18n (Internationalization)](reference/apis/js-apis-i18n.md) - [@ohos.intl (Internationalization)](reference/apis/js-apis-intl.md) - [@ohos.resourceManager (Resource Manager)](reference/apis/js-apis-resource-manager.md) - - Resource Scheduling + - Background Task - [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](reference/apis/js-apis-reminderAgentManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) @@ -987,8 +1013,8 @@ - [@ohos.rpc (RPC)](reference/apis/js-apis-rpc.md) - [@ohos.wifiManager (WLAN)](reference/apis/js-apis-wifiManager.md) - [@ohos.wifiManagerExt (WLAN Extension)](reference/apis/js-apis-wifiManagerExt.md) - - [@ohos.wifi (To Be Deprecated)](reference/apis/js-apis-wifi.md) - - [@ohos.wifiext (To Be Deprecated)](reference/apis/js-apis-wifiext.md) + - [@ohos.wifi (To Be Deprecated Soon)](reference/apis/js-apis-wifi.md) + - [@ohos.wifiext (To Be Deprecated Soon)](reference/apis/js-apis-wifiext.md) - tag - [nfctech (Standard NFC Technologies)](reference/apis/js-apis-nfctech.md) - [tagSession (Standard NFC Tag Session)](reference/apis/js-apis-tagSession.md) @@ -1054,7 +1080,7 @@ - [@ohos.account.appAccount (App Account Management)](reference/apis/js-apis-appAccount.md) - [@ohos.account.distributedAccount (Distributed Account Management)](reference/apis/js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md) - - Custom Management + - Customization - [@ohos.configPolicy (Configuration Policy)](reference/apis/js-apis-configPolicy.md) - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](reference/apis/js-apis-enterprise-adminManager.md) @@ -1161,15 +1187,16 @@ - [colorSpaceManager Error Codes](reference/errorcodes/errorcode-colorspace-manager.md) - [Display Error Codes](reference/errorcodes/errorcode-display.md) - [Window Error Codes](reference/errorcodes/errorcode-window.md) - - Media + - Multimedia - [Audio Error Codes](reference/errorcodes/errorcode-audio.md) - [Media Error Codes](reference/errorcodes/errorcode-media.md) - [AVSession Management Error Codes](reference/errorcodes/errorcode-avsession.md) - - Resource Management + - Resource Manager - [I18N Error Codes](reference/errorcodes/errorcode-i18n.md) - [Resource Manager Error Codes](reference/errorcodes/errorcode-resource-manager.md) - - Resource Scheduling + - Background Task - [backgroundTaskManager Error Codes](reference/errorcodes/errorcode-backgroundTaskMgr.md) + - [DeviceUsageStatistics Error Codes](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - [reminderAgentManager Error Codes](reference/errorcodes/errorcode-reminderAgentManager.md) - [workScheduler Error Codes](reference/errorcodes/errorcode-workScheduler.md) - Security @@ -1186,6 +1213,8 @@ - [Preferences Error Codes](reference/errorcodes/errorcode-preferences.md) - File Management - [File Management Error Codes](reference/errorcodes/errorcode-filemanagement.md) + - Telephony Service + - [Telephony Error Codes](reference/errorcodes/errorcode-telephony.md) - Network Management - [Upload and Download Error Codes](reference/errorcodes/errorcode-request.md) - Connectivity @@ -1217,8 +1246,7 @@ - [System Parameter Error Codes](reference/errorcodes/errorcode-system-parameterV9.md) - [USB Error Codes](reference/errorcodes/errorcode-usb.md) - [Update Error Codes](reference/errorcodes/errorcode-update.md) - - [DeviceUsageStatistics Error Codes](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - - Customization Management + - Customization - [Enterprise Device Management Error Codes](reference/errorcodes/errorcode-enterpriseDeviceManager.md) - Language Base Class Library - [Utils Error Codes](reference/errorcodes/errorcode-utils.md) diff --git a/en/application-dev/windowmanager/window-overview.md b/en/application-dev/windowmanager/window-overview.md index 5a2e75770469377d96c58bf93650c7a47a171e3f..a585f4c7cbde39f74123cacb4d76c2a001290539 100644 --- a/en/application-dev/windowmanager/window-overview.md +++ b/en/application-dev/windowmanager/window-overview.md @@ -36,7 +36,9 @@ In OpenHarmony, the **Window** module provides system windows and application wi - A **system window** implements specific functionalities of the system, such as the volume bar, wallpaper, notification panel, status bar, and navigation bar. - An **application window** is related to the application display. Based on the displayed content, application windows are further classified into main windows and subwindows. - A main window shows the application UI and appears on the **Recent tasks** page. - - A subwindow shows auxiliary windows such as dialog boxes and floating windows of an application. It is not displayed on the **Task Management** page. + - A subwindow shows auxiliary windows such as dialog boxes and floating windows of an application. It is not displayed on the **Task Management** page. Its lifecycle follows that of the main window. + + ### Application Window Mode diff --git a/en/device-dev/faqs/faqs-burning.md b/en/device-dev/faqs/faqs-burning.md index 09f3a076e11ad20c3a539746954c3a7221bb62fa..2390fcde0049a6d96f58ae4f25b3ab6599e6233f 100644 --- a/en/device-dev/faqs/faqs-burning.md +++ b/en/device-dev/faqs/faqs-burning.md @@ -4,44 +4,45 @@ ## Mini and Small Systems -### "Error: Opening COMxx: Access denied" Displayed When I Start Burning +### "Error: Opening COMxx: Access denied" Is Displayed When I Start Burning - **Symptom** - + After I click **Burn** and select a serial port, **Error: Opening COMxx: Access denied** is displayed. **Figure 1** Access denied error ![failed-to-open-the-serial-port](figures/failed-to-open-the-serial-port.png) -- **Possible Causes** +- **Possible Causes** + The serial port is in use. - **Solution** 1. Search for the terminal using serial-xx from the drop-down list in the **TERMINAL** panel. - + **Figure 2** Checking whether the serial port is in use - - ![en-us_image_0000001243481989](figures/en-us_image_0000001243481989.png) + ![en-us_image_0000001243481989](figures/en-us_image_0000001243481989.png) + 2. Click the dustbin icon as shown below to disable the terminal using the serial port. - + **Figure 3** Disabling the terminal using the serial port - + ![en-us_image_0000001243082093](figures/en-us_image_0000001243082093.png) 3. Click **Burn**, select the serial port, and start burning images again. - + **Figure 4** Restarting the burning task - + ![en-us_image_0000001198322224](figures/en-us_image_0000001198322224.png) ### The Image Failed To Be Burnt - **Symptom** - + The image failed to be burnt over a serial port. - **Possible Causes** @@ -87,29 +88,28 @@ > > Hi3518E V300: **device\hisilicon\hispark_aries\sdk_liteos\uboot\out\boot\u-boot-hi3518ev300.bin** - 2. Burn the U-Boot file by following the procedures for burning a U-Boot file over USB. - Select the U-Boot files of the corresponding development board for burning by referring to [Burning an Image](../quick-start/quickstart-ide-3516-burn.md). + 2. Burn the U-Boot file. + + Select the U-Boot files of the corresponding development board for burning. For details, see [Burning an Image](../quick-start/quickstart-ide-3516-burn.md). - 3. Log in to the serial port after the burning is complete. + 3. Log in to the serial port after the burning is complete. - **Figure 5** Information displayed through the serial port after the U-Boot file is burnt + **Figure 5** Information displayed through the serial port after the U-Boot file is burnt - ![en-us_image_0000001243484907](figures/en-us_image_0000001243484907.png) + ![en-us_image_0000001243484907](figures/en-us_image_0000001243484907.png) ### Windows-based PC Failed to Be Connected to the Board - **Symptom** - The file image cannot be obtained after clicking **Burn** and selecting a serial port. **Figure 6** Failed to obtain the file image due to network disconnection - + ![en-us_image_0000001198322428](figures/en-us_image_0000001198322428.png) - **Possible Causes** - The board is disconnected from the Windows-based PC. @@ -117,23 +117,55 @@ - **Solution** - 1. Check whether the network cable is properly connected. - 2. Click **Windows Firewall**. + 1. Make sure the network cable is properly connected. - **Figure 7** Setting the firewall + 2. Click **Windows Firewall**. + + **Figure 7** Setting the firewall + ![en-us_image_0000001198162584](figures/en-us_image_0000001198162584.png) 3. Click **Firewall & network protection**. On the displayed page, click **Allow an app through the firewall**. - + **Figure 8** Firewall & network protection + ![en-us_image_0000001198323146](figures/en-us_image_0000001198323146.png) 4. Select Visual Studio Code. - + **Figure 9** Selecting Visual Studio Code + ![en-us_image_0000001198003232](figures/en-us_image_0000001198003232.png) 5. Select the **Private** and **Public** network access rights for Visual Studio Code. - + **Figure 10** Allowing Visual Studio Code to access the network - ![en-us_image_0000001243084579](figures/en-us_image_0000001243084579.png) \ No newline at end of file + + ![en-us_image_0000001243084579](figures/en-us_image_0000001243084579.png) + +### The Development Board Failed to Be Identified by the Burning Tool + +- **Symptom** + + During image burning, the burning tool displays a message indicating that no device is found. + +- **Possible Causes** + + The cable between the Windows computer and the development board is not connected. (The cable required varies. In this example, the USB cable is used.) + + The driver corresponding to the cable between the Windows computer and the development board is not installed. + +- **Solution** + + 1. Make sure the cable between the Windows computer and the development board is connected. + + 2. Open Device Manager in Windows. + + 3. Open the Universal Serial Bus controllers list. + + 4. Check whether the USB device driver has been installed. If an alarm is displayed, the driver has not been installed. + + 5. Depending on the Windows environment, install the desired USB device driver, such as FT23R USB UART Driver. Then try again. + + 6. If any other issue occurs, consult the relevant FAQ entry. + diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index a3025ebd834424ff319aa25f3194609ead2cf1e9..5c220923fef21109d1556e925d96946da2d54c7f 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -74,6 +74,7 @@ Before using the Docker environment, perform the following operations: > > You do not need to obtain the source code for the HPM-based Docker environment. +3. Perform subsequent operations as a user who has the root permission or has been granted the permission to use Docker. ## Standalone Docker Environment diff --git a/en/device-dev/get-code/sourcecode-acquire.md b/en/device-dev/get-code/sourcecode-acquire.md index b4aac7c6be95fb4e79dd94b6c14fde201fea2a56..6e6cf7aec20779e57b7dd0607d6ae8f16295d04b 100644 --- a/en/device-dev/get-code/sourcecode-acquire.md +++ b/en/device-dev/get-code/sourcecode-acquire.md @@ -182,12 +182,12 @@ The table below provides only the sites for downloading the latest OpenHarmony L | Hi3516 solution-Linux (binary)| 3.0 | [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus_linux.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus_linux.tar.gz.sha256) | 418.1 MB | | RELEASE-NOTES | 3.0 | [Download](https://gitee.com/openharmony/docs/blob/OpenHarmony-3.0-LTS/en/release-notes/OpenHarmony-v3.0-LTS.md)| - | - | | **Source Code of the Latest Release**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**| -| Full code base (for mini, small, and standard systems)| 3.2 Beta4 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/code-v3.2-Beta4.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/code-v3.2-Beta4.tar.gz.sha256) | 19.0 GB | -| RK3568 standard system solution (binary)| 3.2 Beta4 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/dayu200_standard_arm32.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/dayu200_standard_arm32.tar.gz.sha256) | 3.2 GB | -| Hi3861 solution (binary)| 3.2 Beta4 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_pegasus.tar.gz.sha256) | 22.6 MB | -| Hi3516 solution-LiteOS (binary)| 3.2 Beta4 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_taurus_LiteOS.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_taurus_LiteOS.tar.gz.sha256)| 293.9 MB | -| Hi3516 solution-Linux (binary)| 3.2 Beta4 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_taurus_Linux.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta4/hispark_taurus_Linux.tar.gz.sha256)| 173.2 MB | -| RELEASE-NOTES | 3.2 Beta4 | [Download](../../release-notes/OpenHarmony-v3.2-beta4.md)| - | - | +| Full code base (for mini, small, and standard systems)| 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz.sha256) | 21.3 GB | +| Hi3861 solution (binary) | 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz.sha256) | 22.9 MB | +| Hi3516 solution-LiteOS (binary)| 3.2 Beta5 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz.sha256) | 293.6 MB | +| Hi3516 solution-Linux (binary) | 3.2 Beta5 | [Download](hispark_taurus_Linux.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_Linux.tar.gz.sha256) | 174.3 MB | +| RK3568 standard system solution (binary) | 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz.sha256) | 3.9 GB | +| RELEASE-NOTES | 3.2 Beta5 | [Download](../../release-notes/OpenHarmony-v3.2-beta5.md)| - | - | | **Compiler Toolchain**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**| | Compiler toolchain| - | [Download](https://repo.huaweicloud.com/openharmony/os/2.0/tool_chain/)| - | - | diff --git a/en/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md b/en/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md index 76820392c8015b557111e0986a82b32579c7e3e3..0bb8a5f39c772167420b88639299f066088f1457 100644 --- a/en/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md +++ b/en/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md @@ -443,7 +443,7 @@ To adapt `OpenHarmony` subsystems, you only need to add related subsystems and c #### Startup Subsystem Adaptation -For the startup subsystem, adapt the `bootstrap_lite`, `syspara_lite`, `appspawn_lite`, and `init_lite` components. Add the corresponding configuration items to the `vendor/bearpi/bearpi_hm_micro/config.json` file, as shown below: +For the startup subsystem, adapt the `bootstrap_lite`, `syspara_lite`, `appspawn_lite`, and `init` components. Add the corresponding configuration items to the `vendor/bearpi/bearpi_hm_micro/config.json` file, as shown below: ``` { @@ -452,7 +452,7 @@ For the startup subsystem, adapt the `bootstrap_lite`, `syspara_lite`, `appspawn { "component": "syspara_lite", "features":[] }, { "component": "bootstrap_lite", "features":[] }, { "component": "appspawn_lite", "features":[] }, - { "component": "init_lite", "features":[] } + { "component": "init", "features":[] } ] }, ``` diff --git a/en/device-dev/subsystems/subsys-boot-init-deviceInfo.md b/en/device-dev/subsystems/subsys-boot-init-deviceInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..fd2c79d06f047628a118cdc137a4acbdfefa67ca --- /dev/null +++ b/en/device-dev/subsystems/subsys-boot-init-deviceInfo.md @@ -0,0 +1,158 @@ +# DeviceInfo Adaptation + +## DeviceInfo parameters and mapping APIs + +| Parameter| API| Description| +|----------|------- |------| +| const.product.devicetype | const char\* GetDeviceType(void) | Obtains the device type.| +| const.product.manufacturer | const char\* GetManufacture(void) | Obtains the device manufacturer.| +| const.product.brand | const char\* GetBrand(void) | Obtains the device brand.| +| const.product.name | const char\* GetMarketName(void) | Obtains the device marketing name.| +| const.build.product | const char\* GetProductSeries(void) | Obtains the device series name.| +| const.product.model | const char\* GetProductModel(void) | Obtains the device authentication model.| +| const.software.model | const char\* GetSoftwareModel(void) | Obtains the device software model.| +| const.product.hardwareversion | const char\* GetHardwareModel(void) | Obtains the device hardware model.| +| const.product.hardwareprofile | const char\* GetHardwareProfile(void) | Obtains the device hardware profile.| +| ohos.boot.sn | const char\* GetSerial(void) | Obtains the serial number (SN) of the device.| +| const.product.software.version | const char\* GetDisplayVersion(void) | Obtains the software version visible to users.| +| const.product.bootloader.version | const char\* GetBootloaderVersion(void) | Obtains the bootloader version of the device.| +| const.product.udid | int GetDevUdid(char \*udid, int size) | Obtains the UDID of the device through **DeviceInfo** or through calculation if the attempt to obtain the UDID through **DeviceInfo** fails.| +| | const char *AclGetSerial(void); | Obtains the SN of the device (with ACL check).| +| | int AclGetDevUdid(char *udid, int size); | Obtains the UDID of the device (with ACL check).| + +## DeviceInfo Source + +### Adaptation of OHOS Fixed-value Parameters + +- OHOS fixed-value parameters: + + ``` + const.ohos.version.security_patch + const.ohos.releasetype + const.ohos.apiversion + const.ohos.fullname + ``` + +- Description of adaptation: + + OHOS fixed-value parameters are filled by the OHOS and do not need to be adapted by vendors. Currently, these parameters are defined in the **/base/startup/init/services/etc/param/ohos_const/ohos.para** file. + +### Adaptation of Vendor Fixed-value Parameters + +- Vendor fixed-value parameters: + + ``` + const.product.devicetype + const.product.manufacturer + const.product.brand + const.product.name + const.build.product + const.product.model + const.software.model + const.product.hardwareversion + const.product.hardwareprofile + const.product.software.version + const.product.bootloader.version + const.build.characteristics + ... ... + + ``` + + +- Description of adaptation: + + Adapt parameters in the **vendor** directory based on actual requirements. + + (1) Take RK3568 as an example for standard-system devices. Adapt parameters in the **/vendor/hihope/rk3568/etc/para/hardware_rk3568.para** file and install the file to the specified directory. + + ``` + ohos_prebuilt_etc("para_for_chip_prod") { + source = "./para/hardware_rk3568.para" + install_images = [ chip_prod_base_dir ] + relative_install_dir = "para" + part_name = "product_rk3568" + } + ``` + + (2) For mini- and small-system devices, adapt parameters in the respective **hals/utils/sys_param/vendor.para** file. For example: + + ``` + const.product.manufacturer=Talkweb + + const.product.brand=Talkweb + + const.product.name=Niobe + + const.build.product=Niobe + + const.product.model=Niobe407 + + const.software.model="2.0.0" + + const.product.hardwareversion="1.0.0" + + const.product.hardwareprofile="RAM:192K,ROM:1M,ETH:true" + ... ... + ``` + +### Adaptation of Vendor Dynamic-value Parameters + +- Currently, three ways are provided to obtain vendor dynamic-value parameters: cmdline, macro definition, and **BUILD.gn** definition. + + 1. cmdline: Values that are read from cmdline include **ohos.boot.hardware**, **ohos.boot.bootslots**, and **ohos.boot.sn**. The way to obtain **ohos.boot.sn** differs according to the system type as follows: + + (1) For standard-system devices: **ohos.boot.sn** is read from cmdline (generated by U-Boot). If the SN is obtained, the value is directly read; if the file path is obtained, the value is read from the file. If the preceding attempt fails, the value is read from the default SN files; that is, **/sys/block/mmcblk0/device/cid** and **/proc/bootdevice/cid**. + + (2) For mini- and small-system devices: These devices may come with their own special algorithms. Therefore, **HalGetSerial()** can be used to obtain the SN from the **hal_sys_param.c** file in the **hals/utils/sys_param** directory. + + 2. Macro definition: Obtain parameter values by compiling macro definitions. Currently, this mode is available only for mini- and small-system devices. For example: + + ``` + defines = [ + "INCREMENTAL_VERSION=\"${ohos_version}\"", + "BUILD_TYPE=\"${ohos_build_type}\"", + "BUILD_USER=\"${ohos_build_user}\"", + "BUILD_TIME=\"${ohos_build_time}\"", + "BUILD_HOST=\"${ohos_build_host}\"", + "BUILD_ROOTHASH=\"${ohos_build_roothash}\"", + ] + ``` + + 3. **BUILD.gn** definition: Obtain parameter values from the **/base/startup/init/services/etc/BUILD.gn** file. For example: + + ``` + if (target_cpu == "arm64") { + extra_paras += [ "const.product.cpu.abilist=arm64-v8a" ] + } + if (build_variant == "user") { + extra_paras += [ + "const.secure=1", + "const.debuggable=0", + ] + } else if (build_variant == "root") { + extra_paras += [ + "const.secure=0", + "const.debuggable=1", + ] + } + if (device_type != "default") { + extra_paras += [ + "const.product.devicetype=${device_type}", + "const.build.characteristics=${device_type}", + ] + } + module_install_dir = "etc/param" + } + ``` +#### Notes + + (1) For small-system devices, add the compilation of **vendor.para** to the **hals/utils/sys_param/BUILD.gn** file. + + ``` + copy("vendor.para") { + sources = [ "./vendor.para" ] + outputs = [ "$root_out_dir/vendor/etc/param/vendor.para" ] + } + ``` + + (2) For mini-system devices, a file system is not available and therefore, the **hal_sys_param.c** and **vendor.para** files are converted into header files and are compiled to the system during compilation. diff --git a/en/device-dev/subsystems/subsys-boot-init-jobs.md b/en/device-dev/subsystems/subsys-boot-init-jobs.md index 0a9bc5be6ee4270204bc0899dc825fce38a1617e..bd8ab114595085b855a2b60f6d84f17d74c4936d 100644 --- a/en/device-dev/subsystems/subsys-boot-init-jobs.md +++ b/en/device-dev/subsystems/subsys-boot-init-jobs.md @@ -5,7 +5,7 @@ A job is a set of commands in the **.cfg** file of the init module. A maximum of ### Basic Concepts A job can be configured in the **init.cfg** file or the custom **.cfg** file of the module. The parser of the init process aggregates commands of the jobs with the same name into one job. For jobs with the same name, the init process only ensures that the commands in the **init.cfg** file are executed in preference. It does not guarantee the execution sequence of commands in other **.cfg** files. -- Common job +- Basic job A job executed in a fixed phase during init process startup, for example, pre-init, init, or post-init. - pre-init: pre-initialization phase. Key services on which other services depend, such as ueventd, watchdog, and hilogd, are started in this phase. The mounting of data partitions is also done in this phase. @@ -20,7 +20,21 @@ A job can be configured in the **init.cfg** file or the custom **.cfg** file of A job triggered based on specific conditions. You can add conditions to a job so that the job is executed when the conditions are met. - A condition is a combination of system parameter values and supports operations such as **&&** and **||**, for example, **"condition": "sys.usb.config = none && sys.usb.configfs = 0"**. When defining commands for a job, you can add attributes in the format of **param:xxx** to form different commands. + A condition is a combination of system parameter values. It supports operations such as **&&** and **||** as well as matching of any parameter values by using the wildcard character (*). + + Generally, you can configure a condition in the format shown below: + + ``` + "condition": "sys.usb.config = none && sys.usb.configfs = 0" + ``` + + If you need to enable parameter checking in the boot phase, configure the condition as follows: + + ``` + "condition": "boot && const.debuggable=1" + ``` + + When defining commands for a job, you can add attributes in the format of **param:xxx** to form different commands. ### Constraints With the system parameter module, the standard system is able to support basic, conditional, and custom jobs. The small system supports only basic jobs. @@ -29,881 +43,80 @@ With the system parameter module, the standard system is able to support basic, ### Use Cases A job is a command set, where you can manage the commands to be executed. A maximum of 4096 commands can be added to a command set. During the init startup process, the execution of jobs helps ensure normal running of services. -### Parameters +### Parameter Description **Table 1** Command set description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Command - - - Format and Example - - - Description - - - Supported System Type - -
- mkdir - - mkdir target folder [mode] [owner] [group]
Example:
mkdir /storage/myDirectory
mkdir /storage/myDirectory 0755 root root -
- Creates a folder. mkdir and the target folder must be separated by only one space. Folders cannot be created recursively. - - Small and standard systems -
- chmod - - chmod permission target
Example:
chmod 0600 /storage/myFile.txt
chmod 0750 /storage/myDir -
- Modifies the permission, which must be in the 0xxx format. chmod, permission, and target must be separated by only one space. - - Small and standard systems -
- chown - - chown uid gid target
Example:
chown 900 800 /storage/myDir
chown 100 100 /storage/myFile.txt -
- Modifies the owner group. chown, uid, gid, and target must be separated by only one space. - - Small and standard systems -
- mount - - mount fileSystemType src dst flags data
Example:
mount vfat /dev/mmcblk0 /sdc rw,umask=000
mount jffs2 /dev/mtdblock3 /storage nosuid -
- Mounts devices. Every two parameters must be separated by only one space.
For details about flags, see the mountFlagMap[] array of the mountFlagMap function in base/startup/init/services/init/init_common_cmds.c. The data field is optional. -
- Small and standard systems -
- start - - start serviceName
Example:
start foundationstart -
- Starts services. serviceName must be contained in the services array. - - Small and standard systems -
- export - - export key value
Example:
export TEST /data/test -
- Sets environment variables. key and value respectively indicate the environment variable and its value. - - Small and standard systems -
- rm - - rm filename
Example:
rm /data/testfile -
- Deletes a file. filename indicates the absolute file path. - - Small and standard systems -
- rmdir - - rmdir dirname
Example:
rmdir /data/testdir -
- Deletes a directory. dirname indicates the absolute path of the directory. - - Small and standard systems -
- write - - write filename value
Example:
write /data/testfile 0 -
- Writes a file. filename and value respectively indicate the absolute file path and the string to write. - - Standard system -
- stop - - stop servicename
Example:
stop console -
- Stops a service. servicename indicates the name of the service to stop. - - Small and standard systems -
- copy - - copy oldfile newfile
Example:
copy /data/old /data/new -
- Copies a file. oldfile and newfile respectively indicate the old and new absolute file paths. - - Small and standard systems -
- reset - - reset servicename
Example:
reset console -
- Resets a service. servicename indicates the name of the service to reset. If the service has not been started, this command will start the service. If the service is running, the command will stop the service and then restart it. - - Small and standard systems -
- reboot - - reboot subsystem
Example:
reboot updater -
- Restarts the system. subsystem is optional. If it is not specified, the device enters the current system upon restarting. If it is specified, the device enters the corresponding subsystem upon restarting. For example, if you run reboot updater, the device enters the updater subsystem upon restarting. - - Small and standard systems -
- sleep - - sleep time
Example:
sleep 5 -
- Enters the sleep mode. time indicates the sleep time.
To avoid impact on services, exercise caution when running this command. -
- Small and standard systems -
- domainname - - domainname name
Example:
domainname localdomain -
- Sets the domain name. - - Small and standard systems -
- hostname - - hostname name
Example:
hostname localhost -
- Sets the host name. - - Small and standard systems -
- wait - - wait filepath
Example:
wait /data/testfile or wait /data/testfile 5 -
- Waits for commands. The waiting time must not exceed 5 seconds. - - Small and standard systems -
- setrlimit - - setrlimit resource curValue maxValue
Example:
setrlimit RLIMIT_CPU 10 100 -
- Sets resource usage restrictions.
For details, see the resource[] array of the DoSetrlimit function in base/startup/init/services/init/init_common_cmds.c. -
- Small and standard systems -
- exec - - exec Path of the executable file Parameters passed by the executable file
Example:
exec /system/bin/udevadm trigger -
- Runs an executable file. The command must not contain more than 10 parameters. - - Small and standard systems -
- syncexec - - syncexec Path of the executable file Parameters passed by the executable file
Example:
syncexec /system/bin/udevadm trigger -
- Runs an executable file synchronously. The **wait** function will be called to wait for the child process to end. The command must not contain more than 10 parameters. - - Standard system -
- mknode - - mknod name { b | c } Major Minor
Example:
mknod path b 0644 1 9 -
- Creates an index node corresponding to a directory entry and a special file. - - Standard system -
- makedev - - makedev major minor
Example:
makedev -v update -
- Creates a static device node, which is usually in the /dev directory. - - Standard system -
- symlink - - symlink target link_name
Example
symlink /proc/self/fd/0 /dev/stdin -
- Creates a symbolic link. - - Standard system -
- trigger - - trigger jobName
Example
trigger early-fs -
- Triggers a job. - - Standard system -
- insmod - - insmod [-f] [options]
Example
insmod xxx.ko -
- Loads a kernel module file. - - Standard system -
- setparam - - setparam paramname paramvalue
Example:
setparam sys.usb.config hdc -
- Sets system parameters. - - Standard system -
- load_persist_params - - load persist params
Example:
load_persist_params  -
- Loads persist parameters. There must be one and only one space after the load_persist_params command. - - Standard system -
- load_param - - load params
Example:
load_param /data/test.normal.para -
- Loads the parameters from a file to the memory. - - Standard system -
- load_access_token_id - - load_access_token_id  - - Writes the access token to the data/service/el0/access_token/nativetoken.json file. There is one and only one space after load_access_token_id. - - Standard system -
- ifup - - ifup NIC
Example:
ifup eth0 -
- Activates the specified NIC. - - Standard system -
- mount_fstab - - mount_fstab fstab.test
Example:
mount_fstab /vendor/etc/fstab.test -
- Mounts partitions based on the fstab file. - - Standard system -
- umount_fstab - - umount_fstab fstab.test
Example:
umount_fstab /vendor/etc/fstab.test -
- Unmounts partitions based on the fstab file. - - Standard system -
- restorecon - - restorecon file or dir
Example:
restorecon /file -
- Reloads the SELinux context. - - Standard system -
- stopAllServices - - stopAllServices [bool]
Example:
stopAllServices false
stopAllServices -
- Stops all services. - - Standard system -
- umount - - umount path
Example:
umount /vendor -
- Unmounts a mounted device. - - Standard system -
- sync - - sync  - - Writes data to the disk synchronously. There is only one and only one space after sync. - - Standard system -
- timer_start - - timer_start serviceName
Example:
timer_start console -
- Starts the service timer. - - Standard system -
- timer_stop - - timer_stop serviceName
Example:
timer_stop console -
- Stops the service timer. - - Standard system -
- init_global_key - - init_global_key path
Example:
init_global_key /data -
- Initializes the encryption key of the data partition file. - - Standard system -
- init_main_user - - init_main_user - - Encrypts the main user directory. - - Standard system -
- mkswap - - mkswap file
Example:
mkswap /swapfile1 -
- Creates a swap partition on a file or device. - - Standard system -
- swapon - - swapon file
Example:
swapon /swapfile1 -
- Activates the swap space. - - Standard system -
- mksandbox - - mksandbox fileName
Example:
mksandbox system -
- Creates a sandbox. - - Standard system -
- loadcfg - - loadcfg filePath
Example:
loadcfg /patch/fstab.cfg -
- Loads other .cfg files. The maximum size of the target file (only /patch/fstab.cfg supported currently) is 50 KB. Each line in the /patch/fstab.cfg file is a command. The command types and formats must comply with their respective requirements mentioned in this table. A maximum of 20 commands are allowed. - - Small system -
+ | Command| Format and Example| Description| + | -------- | -------- | -------- | + | mkdir | mkdir target folder [mode] [owner] [group]
Example:
mkdir /storage/myDirectory
mkdir /storage/myDirectory 0755 root root| Creates a folder. mkdir and the target folder must be separated by only one space.
System type: small system and standard system| + | chmod | chmod permission target
Example:
chmod 0600 /storage/myFile.txt
chmod 0750 /storage/myDir | Modifies the permission, which must be in the 0xxx format. chmod, permission, and target must be separated by only one space.
System type: small system and standard system| + | chown | chown uid gid target
Example:
chown 900 800 /storage/myDir
chown 100 100 /storage/myFile.txt | Modifies the owner group. chown, uid, gid, and target must be separated by only one space.
System type: small system and standard system| + | mount | mount fileSystemType src dst flags [data]
Example:
mount vfat /dev/mmcblk0 /sdc rw,umask=000
mount jffs2 /dev/mtdblock3 /storage nosuid | Mounts devices. Every two parameters must be separated by only one space. For details about flags, see the mountFlagMap[] function in base/startup/init/services/init/init\_common\_cmds.c. The data field is optional.
System type: small system and standard system| + | start | start serviceName
Example: start foundation| Starts services. serviceName must be contained in the services array.
System type: small system and standard system| + | export | export key value
Example:
export TEST /data/test| Sets environment variables. key and value respectively indicate the environment variable and its value.
System type: small system and standard system| + | rm | rm filename
Example:
rm /data/testfile| Deletes a file. filename indicates the absolute file path.
System type: small system and standard system| + | rmdir | rmdir dirname
Example:
rmdir /data/testdir| Deletes a directory. dirname indicates the absolute path of the directory.
System type: small system and standard system| + | write | write filename value
Example:
write /data/testfile 0| Writes a file. filename and value respectively indicate the absolute file path and the string to write.
System type: small system and standard system| + | stop | stop serviceName
Example:
stop console| Stops a service. servicenamei> indicates the name of the service to stop.
System type: small system and standard system| + | copy | copy oldfile newfile
Example:
copy /data/old /data/new| Copies a file. oldfile and newfile respectively indicate the old and new absolute file paths.
System type: small system and standard system| + | reset | reset serviceName
Example:
reset console| Resets a service. servicename indicates the name of the service to reset. If the service has not been started, this command will start the service. If the service is running, the command will stop the service and then restart it.
System type: small system and standard system| + | reboot | reboot [subsystem]
Example:
reboot updater| Restarts the system. subsystem is optional. If it is not specified, the device enters the current system upon restarting. If it is specified, the device enters the corresponding subsystem upon restarting. For example, if you run reboot updater, the device enters the updater subsystem upon restarting.
System type: small system and standard system| + | sleep | sleep time
Example:
sleep 5| Enters the sleep mode. time indicates the sleep time, which must not exceed 5 seconds.
To avoid impact on services, exercise caution when running this command.
System type: small system and standard system| + | domainname | domainname name
Example:
domainname localdomain| Sets the domain name.
System type: small system and standard system| + | hostname | hostname name
Example:
hostname localhost| Sets the host name.
System type: small system and standard system| + | wait | wait filepath [time]
Example:
wait /data/testfile or wait /data/testfile 5| Waits for commands. time indicates the waiting time, which must not exceed 5 seconds.
System type: small system and standard system| + | setrlimit | setrlimit resource curValue maxValue
Example:
setrlimit RLIMIT_CPU 10 100| Sets resource usage restrictions.
System type: small system and standard system| + | write | write path content
Example:
write /proc/sys/kernel/sysrq 0| Writes a file.
System type: small system and standard system| + | exec | exec Path of the executable file Parameters passed by the executable file
Example:
exec /system/bin/mkdir /data/test.txt| Runs an executable file. This command is called by the system.
System type: small system and standard system| + | syncexec | syncexec Path of the executable file Parameters passed by the executable file
Example:
syncexec /system/bin/udevadm trigger| Runs an executable file synchronously. The **wait** function will be called to wait for the child process to end. The command must not contain more than 10 parameters.
System type: standard system + | mknode |mknod name { b \| c } Major Minor
Example:
mknod path b 0644 1 9| Creates an index node corresponding to a directory entry and a special file.
System type: standard system| + | makedev | makedev major minor
Example:
makedev -v update| Creates a static device node, which is usually in the /dev directory.
System type: standard system| + | symlink | symlink target link_name
Example:
symlink /proc/self/fd/0 /dev/stdin| Creates a symbolic link.
System type: standard system| + | trigger | trigger jobName
Example:
trigger early-fs| Triggers a job.
System type: standard system| + | insmod | insmod [-f] [options]
Example:
insmod xxx.ko| Loads a kernel module file.
System type: standard system| + | setparam | setparam paramName paramValue
Example:
setparam sys.usb.config hdc| Sets system parameters.
System type: standard system| + | load_persist_params | load persist params
Example:
load_persist_params | Loads persist parameters. There must be one and only one space after the load_persist_params command.
System type: standard system| + | load_param | load params
Example:
load_param /data/test.normal.para| Loads the parameters from a file to the memory.
System type: standard system| + | load_access_token_id | load_access_token_id | Writes the access token to the data/service/el0/access_token/nativetoken.json file. There is one and only one space after load_access_token_id.
System type: standard system| + | ifup | ifup NIC
Example:
ifup eth0| Activates the specified NIC.
System type: standard system| + | mount_fstab | mount_fstab fstab.test
Example:
mount_fstab /vendor/etc/fstab.test| Mounts partitions based on the fstab file.
System type: standard system| + | umount_fstab | umount_fstab fstab.test
Example:
umount_fstab /vendor/etc/fstab.test| Unmounts partitions based on the fstab file.
System type: standard system| + | restorecon | restorecon file or dir
Example:
restorecon /file| Reloads the SELinux context.
System type: standard system| + | stopAllServices | stopAllServices [bool]
Example:
stopAllServices false or stopAllServices| Stops all services. The maximum response time is 10 ms by default.
System type: standard system| + | umount |umount path
Example:
umount /vendor| Unmounts a mounted device.
System type: standard system| + | sync | sync | Writes data to the disk synchronously. There is only one and only one space after sync.
System type: standard system| + | timer_start | timer_start serviceName
Example:
timer_start console| Starts the service timer.
System type: standard system| + | timer_stop | timer_stop serviceName
Example:
timer_stop console| Stops a service timer.
System type: standard system| + | init_global_key | init_global_key path
Example:
init_global_key /data| Initializes the encryption key of the data partition file.
System type: standard system| + | init_main_user | init_main_user| Encrypts the main user directory.
System type: standard system| + | mkswap | mkswap file
Example:
mkswap /swapfile1| Creates a swap partition on a file or device.
System type: standard system| + | swapon | swapon file
Example:
swapon /swapfile1| Activates the swap space.
System type: standard system| + | mksandbox | mksandbox fileName
Example:
mksandbox system| Creates a sandbox.
System type: standard system| + | loadcfg | loadcfg filePath
Example:
loadcfg /patch/fstab.cfg| Loads other .cfg files. The maximum size of the target file (only /patch/fstab.cfg supported currently) is 50 KB. Each line in the /patch/fstab.cfg file is a command. The command types and formats must comply with their respective requirements mentioned in this table. A maximum of 20 commands are allowed.
System type: small system| ### Available APIs Job management is a part of the init startup process. It is a process-based function that completely serves the init startup process. It does not provide any functional APIs for other modules. It works in a way similar to command group management and does not provide help for other types of management. The following describes the job management APIs. **Table 2** Description of job parsing APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- API - - Input Parameter - - Return Value - - Description - - Supported System Type -
- void ParseAllJobs(const cJSON *fileRoot) - - const cJSON *fileRoot - - void - - Provides the general entry for parsing jobs. - - Small and standard systems -
- static void ParseJob(const cJSON  *jobItem, Job *resJob) - - const cJSON *jobItem, Job *resJob - - void - - Checks whether a job exists and parses cmds in it. - - Small system -
- int GetCmdLinesFromJson(const cJSON *root, CmdLines **cmdLines) - - const cJSON *root, CmdLines **cmdLines - - int - - Parses cmds in the job. This API is used for the small system. It does not apply to the standard system because the trigger command and condition attribute are involved. - - Small and standard systems -
- int ParseTriggerConfig(const cJSON *fileRoot, int (*checkJobValid)(const char *jobName)) - - const cJSON *fileRoot, int (*checkJobValid)(const char *jobName) - - int - - Parses the trigger command in the job. - - Standard system -
- static int ParseTrigger_(const TriggerWorkSpace *workSpace, const cJSON *triggerItem, int (*checkJobValid)(const char *jobName)) - - const TriggerWorkSpace *workSpace, const cJSON *triggerItem, int (*checkJobValid)(const char *jobName) - - int - - Obtains the job name, condition attribute, and cmds command group. Jobs are stored in a hash table, and commands are stored in a queue structure. - - Standard system -
+| API| Function| Supported System Type| +|:--------|:-----|:------| +|void ParseAllJobs(const cJSON *fileRoot)|Provides the general entry for parsing jobs.| Small and standard systems| +|static void ParseJob(const cJSON *jobItem, Job *resJob)|Checks whether a job exists and parses cmds in it.| Small system| +|int GetCmdLinesFromJson(const cJSON *root, CmdLines **cmdLines)| Parses cmds in the job. This API is used for the small system.
It does not apply to the standard system because the trigger command and condition attribute are involved.| Small and standard systems| +|int ParseTriggerConfig(const cJSON *fileRoot,
int (*checkJobValid)(const char *jobName))|Parses the trigger command in the job.| Standard system| +|static int ParseTrigger_(const TriggerWorkSpace *workSpace,
const cJSON *triggerItem,
int (*checkJobValid)(const char *jobName))|Obtains the job name, condition attribute, and cmds command group.
Jobs are stored in a hash table, and commands are stored in a queue structure.| Standard system| **Table 3** Description of the job triggering APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- API - - Input Parameter - - Return Value - - Description - - Supported System Type -
- void PostTrigger(EventType type, const char *content, uint32_t contentLen) - - EventType type, const char *content, uint32_t contentLen - - void - - Verifies the validity of the job name and sends a job triggering event. - - Standard system -
- static void SendTriggerEvent(int type, const char *content, uint32_t contentLen) - - int type, const char *content, uint32_t contentLen - - void - - Performs functions such as system control and starting or stopping of services based on system parameters. - - Standard system -
- static void DoTriggerCmd(const struct CmdArgs *ctx) - - const struct CmdArgs *ctx - - void - - Executes the trigger command. - - Standard system -
- void DoTriggerExec(const char *triggerName) - - const char *triggerName - - void - - Finds a command group based on the job name and pushes the commands in the command group to the execution queue. This API is available only for the standard system. - - Standard system -
- void DoJob(const char *jobName) - - const char *jobName - - void - - Matches a job based on the job name and invokes DoCmdByIndex to execute the commands in the job. - - Small system -
- void DoCmdByIndex(int index, const char *cmdContent) - - int index, const char *cmdContent - - void - - Combines parameters and commands. - - Small and standard systems -
- -### Development Example +| API| Function| Supported System Type| +|:--------|:-----|:------| +|void PostTrigger(EventType type, const char *content, uint32_t contentLen)|Verifies the validity of the job name and sends a job triggering event.| Standard system| +|static void SendTriggerEvent(int type, const char *content, uint32_t contentLen)|Performs functions such as system control and starting or stopping of services based on system parameters.| Standard system| +|static void DoTriggerCmd(const struct CmdArgs *ctx)|Executes the trigger command.| Standard system| +|void DoTriggerExec(const char *triggerName)|Finds a command group based on the job name and pushes the commands in the command group to the execution queue.
This API is available only for the standard system.| Standard system| +|void DoJob(const char *jobName)|Matches a job based on the job name and invokes DoCmdByIndex
to execute the commands in the job.| Small system| +|void DoCmdByIndex(int index, const char *cmdContent)|Combines parameters and commands.| Small and standard systems| + +### Example The following is the template for configuring jobs in the .cfg file. You can use it to verify the job management function. ``` { diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md index 9b8204bc76167f4287c9e9f09e8a5a6ebfc9fea1..e6c0316c22cf0f0988f032218e92543c9f7b3acc 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @@ -1,94 +1,109 @@ -# HiSysEvent Logging Configuration +# HiSysEvent Logging Configuration -## Overview -If HiSysEvent logging is required for a component, you need to define a YAML file and [configure the YAML file path](#section123181432175135) in the **bundle.json** file. During compilation, the OpenHarmony compilation framework will use the Python compilation script to parse and verify all the YAML files configured in the **bundle.json** file. On completion, the compilation framework will summarize the configuration information in the YAML files and convert the information into a JSON file named **hisysevent.def**. After that, the compilation framework will put the JSON file to a specified path as the basis for the system to determine whether to log system events. +## Overview -### Basic Concepts + +### Function Introduction + +If HiSysEvent logging is required for a component, you need to define a YAML file and [configure the YAML file path](#verifying-the-yaml-file) in the **bundle.json** file. During compilation, the OpenHarmony compilation framework will use the Python compilation script to parse and verify all the YAML files configured in the **bundle.json** file. On completion, the compilation framework will summarize the configuration information in the YAML files and convert the information into a JSON file named **hisysevent.def**. After that, the compilation framework will put the JSON file to a specified path as the basis for the system to determine whether to log system events. + + +### Basic Concepts Understanding the following concepts would be helpful for you in configuring HiSysEvent logging. -- Event domain - Represents the domain to which an event belongs. It is specified by the **domain** field in the YAML file. For details, see [domain](#section123181432175123) in the example YAML file. +- Event domain
Represents the domain to which an event belongs. It is specified by the **domain** field in the YAML file. For details, see [domain](#writing-a-yaml-file) in the example YAML file. -- Event name - Indicates the events in an event domain. For details, see [EVENT\_NAMEA/EVENT\_NAMEB](#section123181432175123) in the example YAML file. +- Event name
Indicates the events in an event domain. For details, see [EVENT\_NAMEA/EVENT\_NAMEB](#writing-a-yaml-file) in the example YAML file. -- Parameter - Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#section123181432175123) in the example YAML file. +- Parameter
Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#writing-a-yaml-file) in the example YAML file. -### Constraints +### Constraints + +Constraints on the event domain, event name, and parameter - Each YAML file can contain only one event domain, and the domain name cannot be the same as that defined in other YAML files. - Zero or more event names can be defined for one event domain. The event names in the same event domain must be unique. -- Multiple parameters can be defined for one event name. The parameters in the same event name must be unique. There must be one and only one parameter named **\__BASE** in each event name. See Table 1 for the fields of this parameter and Table 2 for the fields of other custom parameters. - - **Table 1** Fields in the \__BASE parameter +- Multiple parameters can be defined for one event name. The parameters in the same event name must be unique. There must be only one parameter named **__BASE** in each event name. See Table 1 for the fields of this parameter and Table 2 for the fields of other custom parameters. + **Table 1** Fields in the \__BASE parameter + + | Field| Description| + | -------- | -------- | + | type | Event type. This field is mandatory.
Value:
- FAULT: fault
- STATISTIC: statistics
- SECURITY: security
- BEHAVIOR: user behavior| + | level | Event level. This field is mandatory.
Value:
- CRITICAL: critical
- MINOR: minor| + | tag | Event tag. This field is mandatory.
Rule:
- You can define a maximum of five tags, separated with a space.
- A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.| + | desc | Event name. This field is mandatory.
Rule:
The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).| + + **Table 2** Description of custom parameters + | Field| Description| - | ----- | ----- | - | type | Indicates the type of the event. This field is mandatory.

Value:
  • **FAULT**: fault
  • **STATISTIC**: statistics
  • **SECURITY**: security
  • **BEHAVIOR**: user behavior
| - | level | Indicates the level of the event. This field is mandatory.

Value:
  • **CRITICAL**: critical
  • **MINOR**: minor
| - | tag | Indicates the tag of the event. This field is mandatory.

Rule:
  • You can define a maximum of five tags separated with a space.
  • A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.
| - | desc | Describes the event name. This field is mandatory.

Rule:
  • The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).
| + | -------- | -------- | + | type | Parameter type. This field is mandatory.
Value:
- BOOL
- INT8
- UINT8
- INT16
- UINT16
- INT32
- UINT32
- INT64
- UINT64
- FLOAT
- DOUBLE
- STRING | + | arrsize | Length of the parameter of the array type. This field is optional.
Value:
1-100| + | desc | Parameter description. This field is mandatory.
Rule:
The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).| - **Table 2** Description of custom parameters +## How to Develop - | Field| Description| - | ----- | ----- | - | type | Indicates the type of a parameter. This field is mandatory.

Value:
  • BOOL
  • UINT8
  • UINT16
  • INT32
  • UINT32
  • UINT64
  • FLOAT
  • DOUBLE
  • STRING
| - | arrsize | Specifies the length of the parameter of the array type. This field is optional.

Value range:
  • 1-100
| - | desc | Describes the parameter. This field is mandatory.

Rule:
  • The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).
| +### Writing a YAML File + + +**Writing Rules** + +- Event domain naming rules: + - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). + - The name contains 1 to 16 characters. -## Writing a YAML File +- Event naming rules: + - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). + - The name contains 1 to 32 characters. + - The number of internal event names in an event domain cannot exceed 4096. -### Writing Rules +- Parameter naming rules: + - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). + - The name contains 1 to 48 characters. + - The number of parameters in an event domain cannot exceed 128. -- Event domain naming rules: - - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). - - The name contains 1 to 16 characters. -- Event naming rules: - - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). - - The name contains 1 to 32 characters. - - The number of internal event names in an event domain cannot exceed 4096. -- Parameter naming rules: - - The name must start with a letter and can contain only uppercase letters, digits, and underscores (_). - - The name contains 1 to 32 characters. - - The number of parameters in an event domain cannot exceed 128. -### Example +**Example** -- In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT\_NAMEA** and **EVENT\_NAMEB**. -- **EVENT\_NAMEA** is defined as a critical event of the fault type. The event contains the **NAME1** parameter of the string type, the **NAME2** parameter of the string type, and the **NAME3** parameter of the unsigned short integer type. Therefore, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEA**. -- **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag. +- In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT_NAMEA** and **EVENT_NAMEB**. - ``` - ########################################## - # HiSysEvent definition for MODULEA - ########################################## +- **EVENT\_NAMEA** is defined as a critical event of the fault type. The event contains the **NAME1** parameter of the string type, the **NAME2** parameter of the string type, and the **NAME3** parameter of the unsigned short integer type. Therefore, you can perform [real-time subscription](../subsystems/subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEA**. - domain: MODULEA +- **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](../subsystems/subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag. + + ``` + ########################################## + # the hisysevent definition for module a # + ########################################## + + domain: MODULEA + + EVENT_NAMEA: + __BASE: {type: FAULT, level: CRITICAL, desc: event name a} + NAME1: {type: STRING, desc: name1} + NAME2: {type: STRING, desc: name2} + NAME3: {type: UINT16, desc: name3} + + EVENT_NAMEB: + __BASE: {type: STATISTIC, level: MINOR, tag: tag1 tag2, desc: event name b} + NAME1: {type: UINT16, desc: name1} + NAME2: {type: INT32, desc: name2} + ``` - EVENT_NAMEA: - __BASE: {type: FAULT, level: CRITICAL, desc: event name a} - NAME1: {type: STRING, desc: name1} - NAME2: {type: STRING, desc: name2} - NAME3: {type: UINT16, desc: name3} - EVENT_NAMEB: - __BASE: {type: STATISTIC, level: MINOR, tag: tag1 tag2, desc: event name b} - NAME1: {type: UINT16, desc: name1} - NAME2: {type: INT32, desc: name2} - ``` +### Verifying the YAML File -## Verifying the YAML File -### Configuring the YAML File Path +**Configuring the YAML File Path** + +In the **bundle.json** file, use the **hisysevent_config** attribute to specify the YAML file path. -In the **bundle.json** file, use the ```hisysevent_config``` attribute to specify the YAML file path. ``` { @@ -131,45 +146,47 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif } ``` ->![](../public_sys-resources/icon-note.gif) **Note:** ->The YAML file can be placed in any directory of the component project as needed. You only need to specify the path in the **bundle.json** file. - -### Compiling the YAML File - -- Perform full compilation. - - During full compilation of the system, the configuration in the YAML files of all components are summarized. After the compilation is complete, the **hisysevent.def** file will be generated in the specified directory. +> **NOTE**
+> The YAML file can be placed in any directory of the component project as needed. You only need to specify the path in the **bundle.json** file. - ``` - cd absolute path of the project's root directory - ./build --product-name - ``` - - To obtain the **hisysevent.def** file generated after full compilation, run the following command: +**Compiling YAML Files** - ``` - cd absolute path of the project's root directory - find out -name hisysevent.def -type f - ``` +- Perform full compilation. + - During full compilation of the system, the configurations in the YAML files of all components are summarized. After the compilation is complete, the **hisysevent.def** file will be generated in the specified directory. + + ``` + cd *absolute path of the project's root directory* + ./build --product-name + ``` -- Single-file compilation: + - To obtain the **hisysevent.def** file generated after full compilation, run the following commands: + + ``` + cd absolute path of the project's root directory + find out -name hisysevent.def -type f + ``` - You can also compile the YAML file of a single component by running the following commands: +- Single-file compilation: + You can also compile the YAML file of a single component by running the following commands: - ``` - cd absolute path of the project's root directory - ./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list --def-path - ``` + + ``` + cd absolute path of the project's root directory + ./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list --def-path + ``` - **Table 3** Parameters for single-file compilation + **Table 3** Parameters for single-file compilation + + | Option| Description| + | -------- | -------- | + | --yaml-list | Paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.| + | --def-path | Path of the **hisysevent.def** file generated after compilation.| - | Parameter| Description| - | ------ | ------ | - | --yaml-list | Specifies the paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.| - | --def-path | Specifies the path of the **hisysevent.def** file generated after compilation.| -### Logging and Querying Events +### Logging and Querying Events -1. Push the **hisysevent.def** file to the **/system/etc/hiview/** directory of the device by using the [hdc_std tool](subsys-toolchain-hdc-guide.md). +1. Push the **hisysevent.def** file to the **/system/etc/hiview/** directory of the device by using the [hdc_std tool](../subsystems/subsys-toolchain-hdc-guide.md). -2. Trigger logging of the custom system events in the YAML file. Then, run [hisysevent -l](subsys-dfx-hisysevent-tool.md) to query historical system events to find out if the logging of the custom system events is successful. +2. Trigger logging of the custom system events in the YAML file. Then, run [hisysevent -l](../subsystems/subsys-dfx-hisysevent-tool.md) to query historical system events to find out if the logging of the custom system events is successful. diff --git a/en/device-dev/subsystems/subsys-security-huks-guide.md b/en/device-dev/subsystems/subsys-security-huks-guide.md index 3961b9e71d056d1fb58c036c81addd14739e73eb..f88fdaa1e0907183a518790f47b29e5688d9611d 100644 --- a/en/device-dev/subsystems/subsys-security-huks-guide.md +++ b/en/device-dev/subsystems/subsys-security-huks-guide.md @@ -4,19 +4,17 @@ ### Introduction -OpenHarmony Universal KeyStore (HUKS) provides system-level key management capabilities, ensuring secure management and use of keys throughout their entire lifecycle (generation, storage, use, and destruction). The environment where a key is stored and used is of the most importance to key security. For example, a key in plaintext must be used in a secure environment, such as a Trusted Execution Environment (TEE) or a security chip. - -This document describes how to adapt Hardware Device Interface (HDI) APIs for secure key storage and use environment based on the OpenHarmony HUKS architecture and how to verify these APIs. +OpenHarmony Universal KeyStore (HUKS) provides system-level key management capabilities, ensuring secure management and use of keys throughout their lifecycle (generation, storage, use, and destruction). The environment where a key is stored and used is of the most importance to key security. For example, the key in plaintext must be used in a secure environment, such as a Trusted Execution Environment (TEE) or security chip. This document describes how to configure a secure environment based on the HUKS architecture and how to verify the configuration. HUKS supports key lifecycle management, which covers the following: -1. Generation and import of the key +- Key generation and import -2. Storage of the key +- Key storage -3. Use of the key (including encryption and decryption, signing and verification, key derivation and agreement, hash, and key access control) +- Key use (including encryption and decryption, signing and verification, key derivation and agreement, hash, and key access control) -4. Destruction of the key +- Key destruction ### Basic Concepts @@ -26,7 +24,7 @@ HUKS supports key lifecycle management, which covers the following: - HUKS Core - A functional module that provides the key management service. This module must run in a secure environment, and the keys in plaintext must be kept inside the HUKS Core module throughout the lifecycle. + A functional module that provides the key management service. This module must run in a secure environment, and the keys in plaintext must be kept inside the HUKS Core module throughout their lifecycle. - TEE @@ -34,15 +32,15 @@ HUKS supports key lifecycle management, which covers the following: - Init-Update-Finish - **Init**: initializes data for a key operation. + **Init**: initializes data for a key operation. - **Update**: operates data by segment and returns the result, or appends data. + **Update**: operates data by segment and returns the result, or appends data. - **Finish**: stops operating data by segment or appending data, and returns the result. + **Finish**: finalizes the **Update** operation, and returns the result. ### Working Principles -The following uses the key generation process as an example to describe the communication between the HUKS Service and HUKS Core. Other key operations are similar. +The following uses the key generation process as an example to describe communication between the HUKS Service and HUKS Core. Other key operations are similar. The upper-layer application invokes the HUKS Service through the key management SDK. The HUKS Service invokes the HUKS Core, which invokes the key management module to generate a key. The HUKS Core uses a work key derived from the root key to encrypt the generated key and sends the encrypted key to the HUKS Service. The HUKS Service stores the encrypted key in a file. ![](figure/HUKS-GenerateKey1.png) @@ -76,15 +74,16 @@ The HUKS Core provides KeyStore (KS) capabilities for applications, including ke | [HuksHdiModuleInit()](#hukshdimoduleinit) | Initializes the HUKS Core. | – | –| | [HuksHdiRefresh()](#hukshdirefresh) | Refreshes the root key. | – | –| | [HuksHdiGenerateKey()](#hukshdigeneratekey) | Generates a key. | The key generated must be in the **KeyBlob** format. |generateKey(keyAlias: string, options: HuksOptions)| -| [HuksHdiImportKey()](#hukshdiimportkey) | Import a key in plaintext. | The output parameter must be in the **KeyBlob** format. | importKey(keyAlias: string, options: HuksOptions)| -| [HuksHdiImportWrappedKey()](#hukshdiimportwrappedkey) |Import an encrypted key. | The output parameter must be in the **KeyBlob** format. | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)| +| [HuksHdiImportKey()](#hukshdiimportkey) | Imports a key in plaintext. | The output parameter must be in the **KeyBlob** format. | importKey(keyAlias: string, options: HuksOptions)| +| [HuksHdiImportWrappedKey()](#hukshdiimportwrappedkey) |Imports an encrypted key. | The output parameter must be in the **KeyBlob** format. | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)| | [HuksHdiExportPublicKey()](#hukshdiexportpublickey) | Exports a public key. |– | exportKey(keyAlias: string, options: HuksOptions) | | [HuksHdiInit()](#hukshdiinit) | Initializes data for a key operation. This API is of the Init-Update-Final model. |– | init(keyAlias: string, options: HuksOptions) | | [HuksHdiUpdate()](#hukshdiupdate) | Operates data by segment or appends data for the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the raw data. | update(handle: number, token?: Uint8Array, options: HuksOptions) | -| [HuksHdiFinish()](#hukshdifinish) | Finishes the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the signed data. | finish(handle: number, options: HuksOptions) | +| [HuksHdiFinish()](#hukshdifinish) | Finalizes the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the signed data. | finish(handle: number, options: HuksOptions) | | [HuksHdiAbort()](#hukshdiabort) | Aborts Init-Update-Finish. |– | abort(handle: number, options: HuksOptions) | | [HuksHdiGetKeyProperties()](#hukshdigetkeyproperties) | Obtains key properties. |– | getKeyProperties(keyAlias: string, options: HuksOptions)| -| [HuksHdiAttestKey()](#hukshdiattestkey) | Obtain the key certificate. |The output parameter must be in the **certChain** format. | attestKey(keyAlias: string, options: HuksOptions)| +| [HuksHdiAttestKey()](#hukshdiattestkey) | Obtains the key certificate. |The output parameter must be in the **certChain** format. | attestKey(keyAlias: string, options: HuksOptions)| +| [HuksHdiExportChipsetPlatformPublicKey()](#hukshdiexportchipsetplatformpublickey) | Exports the public key of a chipset key pair. | The output parameters are the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes. | –| - - - @@ -101,10 +100,11 @@ Initializes the HUKS Core, including the lock, encryption algorithm library, aut - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. - + - Other value: The operation fails. + + + -- - - #### HuksHdiRefresh @@ -119,10 +119,11 @@ Refreshes the root key. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. - + - Other value: The operation fails. + + + -- - - #### HuksHdiGenerateKey @@ -168,10 +169,11 @@ Generates a key based on **paramSet**. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. - + - Other value: The operation fails. + + + -- - - #### HuksHdiImportKey @@ -200,7 +202,7 @@ Imports a key in plaintext. Pointer to the parameters for importing the key.

struct HksBlob *keyOut - Pointer to the output parameter, which holds **paramSet** and the key. + Pointer to the output parameter, which holds **paramSet** and the key imported.

@@ -221,7 +223,7 @@ Imports a key in plaintext. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -279,7 +281,7 @@ Imports an encrypted key. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -315,7 +317,7 @@ Exports a public key. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -354,7 +356,7 @@ Initializes data for a key operation. This API is of the Init-Update-Final model - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -398,7 +400,7 @@ Operates data by segment or appends data for the key operation. This API is of t - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -407,7 +409,7 @@ Operates data by segment or appends data for the key operation. This API is of t **API description** -Finishes the key operation. This API is of the Init-Update-Final model. +Finalizes the key operation. This API is of the Init-Update-Final model. **Prototype**
int32_t HuksHdiFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);
@@ -442,7 +444,7 @@ Finishes the key operation. This API is of the Init-Update-Final model. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -472,7 +474,7 @@ Aborts Init-Update-Finish. When an error occurs in any of the **Init**, **Update - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -502,7 +504,7 @@ Obtains key properties. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. - - - @@ -543,7 +545,50 @@ Obtains the key certificate. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other value: The operation fails. + + +- - - + +#### HuksHdiExportChipsetPlatformPublicKey + +**API description** + +Exports the public key of a chipset key pair. + +**Prototype** +
int32_t (*HuksHdiExportChipsetPlatformPublicKey)(const struct HksBlob *salt, enum HksChipsetPlatformDecryptScene scene, struct HksBlob *publicKey);
+
+ Parameters +
+  const struct HksBlob *salt
+  Factor used to derive the chipset key pair.
+  

+ enum HksChipsetPlatformDecryptScene scene + Expected chipset platform decryption scenario. +

+ struct HksBlob *publicKey + The output parameters are the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes. +
+
+

+ +
+ Constraints + + 1. The input parameter **salt** must be of 16 bytes, and the content of the last byte will be ignored and filled by HUKS based on **scene**. + + Currently, the chipset key pairs of HUKS are implemented by software. An ECC P-256 key pair is hard-coded, and the **salt** value is ignored. That is, the derived keys are the same regardless of the **salt**. In the hardware-based implementation of chipset key pairs, **salt** is a factor used to derive the key. That is, the key pair derived varies with the **salt** value. + +
+

+ +
+ Return value + + - **HKS_SUCCESS**: The operation is successful. + + - Other value: The operation fails.
- - - @@ -554,15 +599,15 @@ The directory structure is as follows: ```undefined // base/security/user_auth/services/huks_standard/huks_engine/main -├── BUILD.gn # Build script +├── BUILD.gn # Build script ├── core_dependency # Dependencies of the implementation -└── core # Software implementation of the HUKS Core - ├── BUILD.gn # Build script +└── core # Software implementation of the HUKS Core + ├── BUILD.gn # Build script ├── include └── src ├── hks_core_interfaces.c # Adaptation of the HDI to the HUKS Core - └── hks_core_service.c # Specific implementation - └── ... # Other function code + └── hks_core_service.c # Specific implementation + └── ... # Other function code ``` Init-Update-Finish must be used to implement HUKS Core APIs. The following provides the development procedure of Init-Update-Finish and sample code of the HUKS Core. You can refer to the following code to implement all HDI APIs. @@ -641,7 +686,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com } ``` -2. Obtain the context based on the handle, and pass in data slices to obtain the operation result or append data. +2. Obtain the context based on the handle, and pass in data by segment or append data to obtain the operation result. ```c // Implement Update(). @@ -707,7 +752,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com } ``` -3. Finish the key operation to obtain the result, and destroy the handle. +3. Finalize the key operation to obtain the result, and destroy the handle. ```c // Implement Finish(). @@ -868,7 +913,7 @@ The JS test code is as follows. If the entire process is successful, the HDI API var result = huks.update(handle, options) ``` -5. Call **finish()** to finish the operation. +5. Call **finish()** to finalize the operation. ```js var properties = new Array(); diff --git a/en/readme/distributed-hardware.md b/en/readme/distributed-hardware.md index 1da23097f88ddd0cbef48ef41ac8667b9af5004b..eac2d2b1811a3dcc2c59e51c45af788d0abc42db 100644 --- a/en/readme/distributed-hardware.md +++ b/en/readme/distributed-hardware.md @@ -4,7 +4,11 @@ ### **Distributed Hardware Subsystem** -The distributed hardware subsystem manages hardware information of all the devices in a Super Device so that the hardware capabilities can be shared and called across devices. +Super Device allows multiple devices to collaborate with each other to provide optimal user experience. + +The distributed hardware subsystem shares peripheral capabilities between devices in a Super Device. It manages the hardware information of each device in a virtual hardware resource pool and centrally shares and schedules the hardware capabilities across devices. The distributed hardware subsystem breaks device boundaries and redefines product forms and user experience through software. For example, you can display the content of your smartphone on a TV screen, and leverage the smartphone cameras to provide enhanced video recording capabilities for your PC. + +The distributed hardware platform uses a hardware virtualization component to implement hardware resource pooling of all devices in a Super Device. Each device has a virtual hardware instance registered with the platform. The hardware virtualization component implements the interaction between the virtual hardware and physical hardware to complete the control over the hardware and data transmission. Hardware resource pooling implements hardware virtualization over the hardware device interface (HDI). Each service subsystem at the service layer can use distributed hardware like using local hardware. ### Architecture @@ -24,15 +28,15 @@ foundation/distributedhardware ### DeviceManager -DeviceManager provides authentication and networking for devices of a Super Device, including discovering distributed devices, performing authentication, and listening for device online/offline status. +OpenHarmony DeviceManager provides authentication and networking capabilities for distributed devices and provides a set of APIs for detecting the online/offline device status, and discovering and authenticating distributed devices. The DeviceManager implements trusted status management, online/offline status management, device discovery, and authentication management. The discovered and authenticated devices can form a Super Device. In the Super Device, hardware resources are automatically synchronized to all devices and uniformly managed by the distributed hardware subsystem. ### Distributed Hardware Framework -As an information management component of the distributed hardware subsystem, the distributed hardware framework implements unified hardware access, information query, and hardware enablement. +The distributed hardware framework provides information management capabilities for the distributed hardware subsystem. It implements unified hardware access, query, and enablement for the distributed hardware subsystem. ### Distributed Camera -The distributed camera component implements collaboration of cameras of multiple devices that form a Super Device. Instead of directly interacting with applications, the distributed camera component only provides C++ interfaces for the distributed hardware framework. Applications can call the APIs of the camera framework to use the distributed camera component to operate cameras of other devices, just like operating a local camera. +Distributed camera implements collaboration of cameras of multiple devices that form a Super Device. The distributed camera component provides C++ interfaces for the distributed hardware framework, but not directly interacting with applications. Applications can call the APIs of the camera framework to use the distributed camera component to operate cameras of other devices, just like operating a local camera. ### Distributed Screen diff --git a/en/release-notes/OpenHarmony-v3.0.8-LTS.md b/en/release-notes/OpenHarmony-v3.0.8-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..e61a09b68aaa944c164975b7bc2cafd236807c01 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.0.8-LTS.md @@ -0,0 +1,120 @@ +# OpenHarmony 3.0.8 LTS + + +## Version Description + +OpenHarmony 3.0.8 LTS is a maintenance version of OpenHarmony 3.0 LTS. It has rectified certain issues detected in OpenHarmony 3.0.7 LTS. + + +## Version Mapping + + **Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.0.8 LTS | NA | +| (Optional) HUAWEI DevEco Studio| 3.0 Beta3 for OpenHarmony | Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| 3.0 Release | Recommended for developing OpenHarmony smart devices| + + +## Source Code Acquisition + + +### Prerequisites + +1. Register your account with Gitee. + +2. Register an SSH public key for access to Gitee. + +3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information. + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. Run the following commands to install the **repo** tool: + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command. + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### Acquiring Source Code Using the repo Tool + +**Method 1 (recommended)**: Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.) + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.8-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**Method 2**: Use the **repo** tool to download the source code over HTTPS. + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.8-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### Acquiring Source Code from Mirrors + + **Table 2** Mirrors for acquiring source code + +| LTS Code| Version| Mirror| SHA-256 Checksum| +| -------- | -------- | -------- | -------- | +| Full code base (for mini, small, and standard systems)| 3.0.8 | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/code-v3.0.8-LTS.tar.gz)| [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/code-v3.0.8-LTS.tar.gz.sha256) | +| Standard system Hi3516 solution (binary)| 3.0.8 | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/standard.tar.gz) | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/standard.tar.gz.sha256) | +| Mini system Hi3861 solution (binary)| 3.0.8 | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_pegasus.tar.gz) | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_pegasus.tar.gz.sha256) | +| Small system Hi3516 solution - LiteOS (binary)| 3.0.8 | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus.tar.gz) | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus.tar.gz.sha256) | +| Small system Hi3516 solution - Linux (binary)| 3.0.8 | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus_linux.tar.gz) | [Download](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus_linux.tar.gz.sha256) | + + +## What's New + + +### Feature Updates + +This version does not involve feature updates. + + +### API Updates + +This version does not involve API updates. + + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +## Fixed Security Vulnerabilities + + **Table 3** Fixed security vulnerabilities + +| Issue No.| Description| PR Link| +| -------- | -------- | -------- | +| I5UHRW | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-41218, CVE-2022-3424, CVE-2022-42328, CVE-2022-3643, and CVE-2022-47946| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/647) | +| I648XK | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3169| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/561) | +| I5QBIA | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-1184 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/475) | +| I62G8K | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-42895 and CVE-2022-42896| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/545) | +| I63VI6 | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-41858| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/570) | +| I63VID | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-45934, CVE-2022-4129, CVE-2022-4378, CVE-2022-3108, CVE-2022-47518, CVE-2022-47521, CVE-2022-47519, and CVE-2022-47520| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/587) | +| I65INV | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-4139 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/568) | +| I66Y94 | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-3105, CVE-2022-3104, CVE-2022-3115, CVE-2022-3113, and CVE-2022-3112 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/580) | +| I66Y9Y | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3106 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/593) | +| I66YAD | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3107 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/591) | +| I6A4HN | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-20568| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/630) | +| I6A4IZ | Security vulnerability of the kernel_linux_5.10 component: CVE-2023-20928| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/654) | +| I6B0AN | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-4696| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/664) | +| I6B0B4 | Security vulnerability of the kernel_linux_5.10 component: CVE-2023-23559, CVE-2023-0179, CVE-2023-23454, and CVE-2023-23455| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/662) | +| I65R5Q | Security vulnerability of the third_party_python component: CVE-2022-45061| [PR](https://gitee.com/openharmony/third_party_python/pulls/40) | +| I6494T | Security vulnerabilities of the third_party_libxml2 component: CVE-2022-40303 and CVE-2022-40304| [PR](https://gitee.com/openharmony/third_party_libxml2/pulls/32) | +| I5ZYY3 | Security vulnerability of the third_party_pixman component: CVE-2022-44638| [PR](https://gitee.com/openharmony/third_party_pixman/pulls/12) | +| I5UHVA | Security vulnerability of the third_party_u-boot component: CVE-2022-2347| [PR](https://gitee.com/openharmony/third_party_u-boot/pulls/63) | diff --git a/en/release-notes/OpenHarmony-v3.1.6-release.md b/en/release-notes/OpenHarmony-v3.1.6-release.md new file mode 100644 index 0000000000000000000000000000000000000000..c72fcf84a808419feb33aec2f73cb8dfdc841f76 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.1.6-release.md @@ -0,0 +1,140 @@ +# OpenHarmony 3.1.6 Release + + +## Version Description + +OpenHarmony 3.1.6 Release provides enhanced system security over OpenHarmony 3.1.5 Release by rectifying memory leak issues, certain known vulnerabilities in open-source components such as Linux kernel, and system stability issues. The matching SDK version is also updated. + + +## Version Mapping + + **Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.1.6 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.12.5 (API Version 8 Release)| This toolkit is intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions.
To use the Full SDK, you must manually obtain it from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../application-dev/quick-start/full-sdk-switch-guide.md).| +| Public SDK | Ohos_sdk_public 3.1.12.5 (API Version 8 Release)| This toolkit is intended for application developers and does not contain system APIs that require system permissions.
It is provided as standard in DevEco Studio 3.0 Beta4 or later.| +| (Optional) HUAWEI DevEco Studio| 3.1 Preview for OpenHarmony| Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| 3.0 Release| Recommended for developing OpenHarmony smart devices| + + +## Source Code Acquisition + + +### Prerequisites + +1. Register your account with Gitee. + +2. Register an SSH public key for access to Gitee. + +3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information. + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. Run the following commands to install the **repo** tool: + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command. + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### Acquiring Source Code Using the repo Tool + +**Method 1 (recommended)** + +Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.) + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.6-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**Method 2** + +Use the **repo** tool to download the source code over HTTPS. + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.6-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### Acquiring Source Code from Mirrors + +**Table 2** Mirrors for acquiring source code + +| Source Code| Version| Mirror| SHA-256 Checksum| +| -------- | -------- | -------- | -------- | +| Full code base (for mini, small, and standard systems)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/code-v3.1.6-Release.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/code-v3.1.6-Release.tar.gz.sha256) | +| Hi3516 standard system solution (binary)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_hi3516.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_hi3516.tar.gz.sha256) | +| RK3568 standard system solution (binary)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_rk3568.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_rk3568.tar.gz.sha256) | +| Hi3861 mini system solution (binary)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_pegasus.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_pegasus.tar.gz.sha256) | +| Hi3516 small system solution - LiteOS (binary)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus.tar.gz.sha256) | +| Hi3516 small system solution - Linux (binary)| 3.1.6 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus_linux.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus_linux.tar.gz.sha256) | +| Full SDK package for the standard system (macOS)| 3.1.12.5 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-full.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-full.tar.gz.sha256) | +| Full SDK package for the standard system (Windows/Linux)| 3.1.12.5 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-full.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-full.tar.gz.sha256) | +| Public SDK package for the standard system (macOS)| 3.1.12.5 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-public.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-public.tar.gz.sha256) | +| Public SDK package for the standard system (Windows/Linux)| 3.1.12.5 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-public.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-public.tar.gz.sha256) | + + +## What's New + +This version has the following updates to OpenHarmony 3.1.5 Release. + + +### Feature Updates + +This version does not involve feature updates. + +### API Updates + +This version does not involve API updates. + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +### Resolved Issues + +**Table 3** Resolved issues + +| Subsystem | Description | +| ------------------ | ------------------------------------------------------------ | +| Application subsystem | The JS crash occurs multiple times in the updateCallTimeList stack of the com.ohos.callui application. ([I5LWIW](https://gitee.com/openharmony/applications_call/issues/I5LWIW))| +| Globalization subsystem | The exception stack libglobal_resmgr.z.so occurs multiple times in the com.ohos.launch thread of the key process com.ohos.launcher. ([I5LT0M](https://gitee.com/openharmony/global_resource_management/issues/I5LT0M))
The exception stack libglobal_resmgr.z.so occurs multiple times in the 2.ui thread of the com.ohos.permissionmanager process. ([I68J7P](https://gitee.com/openharmony/global_resource_management/issues/I68J7P))| +| Misc services subsystem| The CPP crash occurs in the com.example.kikakeyboard process of libinputmethod_client.z.so. ([I66W3B](https://gitee.com/openharmony/inputmethod_imf/issues/I66W3B))
The CPP crash occurs during a pressure test using a tool. ([I65K13](https://gitee.com/openharmony/inputmethod_imf/issues/I65K13))| +| Distributed hardware | The JS crash occurs multiple times in com.ohos.devicemanagerui. ([I69LD9](https://gitee.com/openharmony/distributedhardware_device_manager/issues/I69LD9))| +| DSoftBus | Media resources of the peer device cannot be displayed after the distributed Gallery network is restarted. ([I674LD](https://gitee.com/openharmony/applications_photos/issues/I674LD))| + + +### Fixed Security Vulnerabilities + +**Table 4** Fixed security vulnerabilities + +| Issue No.| Description| PR Link| +| -------- | -------- | -------- | +| I5UI5A | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-41218, CVE-2022-3424, CVE-2022-42328, CVE-2022-3643, and CVE-2022-47946| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/646) | +| I69WX6 | Security vulnerability of the ffmpeg component: CVE-2022-3341 | [PR](https://gitee.com/openharmony/third_party_ffmpeg/pulls/74) | +| I68JS0 | Security vulnerability of the ffmpeg component: CVE-2022-3109 | [PR](https://gitee.com/openharmony/third_party_ffmpeg/pulls/71) | +| I671DT | Security vulnerabilities of the curl component: CVE-2022-43551 and CVE-2022-43552 | [PR](https://gitee.com/openharmony/third_party_curl/pulls/99) | +| I6A4YJ | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-20568 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/629) | +| I6A55C | Security vulnerability of the kernel_linux_5.10 component: CVE-2023-0047 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/631) | + +## Known Issues + +**Table 5** Known issues + +| Issue No. | Description | Impact | To Be Resolved By| +| ------------------------------------------------------------ | ---------------------------------------------------------- | ---------------- | ------------ | +| [I6AF0Y](https://gitee.com/openharmony/ability_ability_runtime/issues/I6AF0Y) | When two windows are paired in split-screen mode, if one window is closed, the other window is also closed.| Exiting the split-screen mode does not take effect.| 2023/02/15 | diff --git a/en/release-notes/OpenHarmony-v3.2-beta1.md b/en/release-notes/OpenHarmony-v3.2-beta1.md index 985ec8a61782ef253cda113dbfd2988da683317b..f682e1d71a830dc70cec8da02492f19f99fa89db 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta1.md +++ b/en/release-notes/OpenHarmony-v3.2-beta1.md @@ -185,27 +185,27 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Subsystem| Sample| Introduction| Programming Language| | -------- | -------- | -------- | -------- | -| ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | This sample simulates a minesweeper game that calls mouse event-related APIs.| eTS | -| ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| eTS | -| DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in eTS.| eTS | -| ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| eTS | +| ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | This sample simulates a minesweeper game that calls mouse event-related APIs.| ArkTS | +| ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| ArkTS | +| DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in ArkTS.| ArkTS | +| ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| ArkTS | | Graphics| [JsWebGL](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) | This sample shows how to use WebGL APIs to draw pentagrams and rectangles by invoking GPU resources.| JS | -| ArkUI | [Clock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | This sample exemplifies how to implement a simple clock application using the eTS UI capability.| eTS | -| Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| eTS | -| Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| eTS | -| Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with eTS.| eTS | -| Ability| [BackgroundTaskManager](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) | This sample simulates the download function. Being processed by the background task management, a download task can continue after the application exits. It stops until the download is complete.| eTS | -| Ability| [BringApp](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode) | This sample uses the **FeatureAbility** APIs to start a system application based on the application's bundle name and ability name.| eTS | -| Media| [VideoPlayer](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | This sample shows how to play a video using the **VideoPlayer** APIs in eTS. It also provides an ability that can be invoked by other applications to play the video.| eTS | -| Ability| [DistributeCalc](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/ArkTSDistributedCalc) | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| eTS | -| Web | [Browser](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser) | This sample uses the stage model and related APIs to show a simple browser.| eTS | -| Ability| [DeviceUsageStatistics](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceUsageStatistics/DeviceUsageStatistics) | This sample shows the device usage statistics.| eTS | -| ArkUI | [AdaptiveCapabilities](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AdaptiveCapabilities) | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | -| ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Game2048) | This sample shows how to develop a 2048 game using the **\** component.| eTS | -| Window Manager| [Window](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings) | This sample shows how to create a window, display an application over another application in the form of a floating window, and display an application on split screens.| eTS | -| Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DataManagement/Preferences) | This sample shows the theme switching function of preferences.| eTS | -| ArkUI | [NativeAPI](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) | This sample shows how to call C++ APIs in eTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and eTS implements UI rendering and re-rendering.| eTS/C++ | -| Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in eTS to set the system language, region, time, and time zone. It also provides locale setting examples.| eTS | +| ArkUI | [ArkTSClock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | This sample exemplifies how to implement a simple clock application using the ArkTS UI capability.| ArkTS | +| Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| ArkTS | +| Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| ArkTS | +| Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with ArkTS.| ArkTS | +| Ability| [WorkScheduler](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) | This sample simulates the update process starting from downloading and saving an update package to sending a notification and installing the update package. Being processed by the background task management, the download task continues after the application exits. It stops until the download is complete.| ArkTS | +| Ability| [AbilityStartMode](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode) | This sample shows how to implement the standard, singleton, and specified ability launch modes in the stage model.| ArkTS | +| Multimedia| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | This sample illustrates media management in ArkTS, including network stream playback, audio and video playback control, and volume adjustment.| ArkTS | +| Ability| [ArkTSDistributedCalc](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/ArkTSDistributedCalc) | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| ArkTS | +| Web | [Browser](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser) | This sample uses the stage model and related APIs to show a simple browser.| ArkTS | +| Ability| [DeviceUsageStatistics](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceUsageStatistics/DeviceUsageStatistics) | This sample shows the device usage statistics.| ArkTS | +| ArkUI | [AdaptiveCapabilities](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AdaptiveCapabilities) | This sample shows multi-device adaptation in ArkTS, including resource qualifiers, atomic layouts, and responsive layouts.| ArkTS | +| ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Game2048) | This sample shows how to develop a 2048 game using the **\** component.| ArkTS | +| Typical Setting Page of One-Time Development for Multi-Device Deployment| [Settings](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings) | This sample shows a typical page for setting an application. The page has different display effects in the small window and large window, reflecting the capability of one-time development for multi-device deployment.| ArkTS | +| Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DataManagement/Preferences) | This sample shows the theme switching function of preferences.| ArkTS | +| ArkUI | [NativeAPI](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) | This sample shows how to call C++ APIs in ArkTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and ArkTS implements UI rendering and re-rendering.| ArkTS/C++ | +| Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in ArkTS to set the system language, region, time, and time zone. It also provides locale setting examples.| ArkTS | For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). diff --git a/en/release-notes/OpenHarmony-v3.2-beta2.md b/en/release-notes/OpenHarmony-v3.2-beta2.md index 2b4a17c9cae653f5bbeb2e0ee24599d6a48d224b..95638ec3fc1b5e246eb34b0d05da5cce6199a2b5 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta2.md +++ b/en/release-notes/OpenHarmony-v3.2-beta2.md @@ -167,28 +167,28 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Subsystem| Name| Introduction| Programming Language| | -------- | -------- | -------- | -------- | -| Ability| MissionManager | This sample calls APIs related to the mission manager to lock, unlock, and clear missions, and switch them to the foreground.| eTS | -| Network management| AirQuality | This sample implements a simple air quality app using JS. The app displays air quality information using line wrapping and historical data in a bar chart.| eTS | -| ArkUI | TransitionAnimation | This sample shows how to implement page transition, component transition, and transition of shared elements.| eTS | -| Application package management| ZipLib | This sample demonstrates the use of **\@ohos.zlib** by constructing the compression and decompression scenarios.| eTS | -| Engineering capabilities| Npm | This sample shows how npm references third-party JS class libraries (mathjs and dayjs) and local libraries.| eTS | -| Data management| DistributedMusicPlayer | In this sample, **fileIo** is used to obtain an audio file; **AudioPlayer** is used to play music, pause the playback, and play the next or previous song; **DeviceManager** is used to display the distributed device list and hop music playback across devices.| eTS | -| ArkUI | PatternLock | This sample shows how to use the **\** component to implement password setting, verification, and resetting.| eTS | -| Security| UserAuth | This sample shows how to implement facial authentication.| eTS | -| Security| Cipher | This sample shows how to use cipher algorithms, including Rivest-Shamir-Adleman (RSA) and Advanced Encryption Standard (AES).| eTS | -| Graphics| Screen | This sample shows how to use APIs to listen for screen quantity changes, create and destroy virtual screens, and read and display screen attributes.| eTS | -| ArkUI | Search | This sample shows how to use the **\** component to implement a search page.| eTS | -| Device management| USBManager | This sample shows how to use USB device management, including listening for USB device insertion and removal events and display of USB device information.| eTS | -| Data management| DistributedDataGobang | This sample shows Gobang, a popular game played with black and white stones on a go board, developed using the distributed data management function. | eTS | -| Multimedia| Image | This sample provides an Image Processing app, using which you can read images from the local device, obtain image information, and rotate images.| eTS | -| Security| AbilityAccessCtrl | This sample shows how **@ohos.abilityAccessCtrl** works to implement application permission control.| eTS | -| Network management| WebSocket | This sample shows how to use WebSocket, including the connection and disconnection between the client and the server, and the receiving and sending of client data.| eTS | -| Connectivity| Bluetooth | Bluetooth is a short-range wireless technology used to implement communication between fixed and mobile devices over low-cost short-distance wireless connections. This sample describes how to discover, pair, and unpair Bluetooth devices.| eTS | -| Multimedia| GamePuzzle | This puzzle game app is developed based on the **\** component. It uses the `Image` and `MediaLibrary` APIs to obtain and crop images.| eTS | -| Network management| UploadDownload | This sample uses the upload and download APIs to implement file storage.| eTS | -| Device management| Location | This sample uses the orientation sensor and GPS to obtain the current location information.| eTS | -| Telephony| Observer | This sample demonstrates how to use observer APIs to subscribe to network status, signal status, call status, cellular data, and SIM card status changes.| eTS | -| ArkUI | AdaptiveCapabilities | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | +| Ability| MissionManager | This sample calls APIs related to the mission manager to lock, unlock, and clear missions, and switch them to the foreground.| ArkTS | +| Network management| AirQuality | This sample implements a simple air quality app using JS. The app displays air quality information using line wrapping and historical data in a bar chart.| ArkTS | +| ArkUI | TransitionAnimation | This sample shows how to implement page transition, component transition, and transition of shared elements.| ArkTS | +| Application package management| ZipLib | This sample demonstrates the use of **\@ohos.zlib** by constructing the compression and decompression scenarios.| ArkTS | +| Engineering capabilities| Npm | This sample shows how npm references third-party JS class libraries (mathjs and dayjs) and local libraries.| ArkTS | +| Data management| DistributedMusicPlayer | In this sample, **fileIo** is used to obtain an audio file; **AudioPlayer** is used to play music, pause the playback, and play the next or previous song; **DeviceManager** is used to display the distributed device list and hop music playback across devices.| ArkTS | +| ArkUI | PatternLock | This sample shows how to use the **\** component to implement password setting, verification, and resetting.| ArkTS | +| Security| UserAuth | This sample shows how to implement facial authentication.| ArkTS | +| Security| Cipher | This sample shows how to use cipher algorithms, including Rivest-Shamir-Adleman (RSA) and Advanced Encryption Standard (AES).| ArkTS | +| Graphics| Screen | This sample shows how to use APIs to listen for screen quantity changes, create and destroy virtual screens, and read and display screen attributes.| ArkTS | +| ArkUI | Search | This sample shows how to use the **\** component to implement a search page.| ArkTS | +| Device management| USBManager | This sample shows how to use USB device management, including listening for USB device insertion and removal events and display of USB device information.| ArkTS | +| Data management| DistributedDataGobang | This sample shows Gobang, a popular game played with black and white stones on a go board, developed using the distributed data management function. | ArkTS | +| Multimedia| Image | This sample provides an Image Processing app, using which you can read images from the local device, obtain image information, and rotate images.| ArkTS | +| Security| AbilityAccessCtrl | This sample shows how **@ohos.abilityAccessCtrl** works to implement application permission control.| ArkTS | +| Network management| WebSocket | This sample shows how to use WebSocket, including the connection and disconnection between the client and the server, and the receiving and sending of client data.| ArkTS | +| Connectivity| Bluetooth | Bluetooth is a short-range wireless technology used to implement communication between fixed and mobile devices over low-cost short-distance wireless connections. This sample describes how to discover, pair, and unpair Bluetooth devices.| ArkTS | +| Multimedia| GamePuzzle | This puzzle game app is developed based on the **\** component. It uses the `Image` and `MediaLibrary` APIs to obtain and crop images.| ArkTS | +| Network management| UploadDownload | This sample uses the upload and download APIs to implement file storage.| ArkTS | +| Device management| Location | This sample uses the orientation sensor and GPS to obtain the current location information.| ArkTS | +| Telephony| Observer | This sample demonstrates how to use observer APIs to subscribe to network status, signal status, call status, cellular data, and SIM card status changes.| ArkTS | +| ArkUI | AdaptiveCapabilities | This sample shows multi-device adaptation in ArkTS, including resource qualifiers, atomic layouts, and responsive layouts.| ArkTS | | ArkUI | JsAdaptiveCapabilities | This sample shows multi-device adaptation in JS, including resource qualifiers, atomic layouts, and responsive layouts.| JS | For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). diff --git a/en/release-notes/OpenHarmony-v3.2-beta3.md b/en/release-notes/OpenHarmony-v3.2-beta3.md index 92ea36158f8854102c3053fc71f31449b158081a..7311d8ff136412cac1f8460dfd21753ded43cf96 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta3.md +++ b/en/release-notes/OpenHarmony-v3.2-beta3.md @@ -190,13 +190,13 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Subsystem| Name| Introduction| Programming Language| | -------- | -------- | -------- | -------- | -| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| eTS | -| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| eTS | -| Ability framework and file management subsystem| [Share](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/CustomShare)| Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| eTS | -| Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| eTS | -| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AppMarket)| This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| eTS | -| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather)| This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| eTS | -| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections)| This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| eTS | +| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| ArkTS | +| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| ArkTS | +| Ability framework and file management subsystem| [CustomShare](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/CustomShare) | Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| ArkTS | +| Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| ArkTS | +| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AppMarket) | This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| ArkTS | +| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather) | This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| ArkTS | +| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| ArkTS | For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). diff --git a/en/release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md b/en/release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md index 13aebd5b337cdf7f6a39b7875350651fffc2bd19..a12696e85e9fc429d76a30fb3947d21d8b9d3b48 100644 --- a/en/release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md +++ b/en/release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md @@ -1,6 +1,6 @@ -# JS API Changes of the Utils Subsystem +# JS API Changes of the Compiler and Runtime Subsystem -The table below lists the APIs changes of the Utils subsystem in OpenHarmony 3.1 Release over OpenHarmony 3.0 LTS. +The table below lists the APIs changes of the compiler and runtime subsystem in OpenHarmony 3.1 Release over OpenHarmony 3.0 LTS. ## API Changes diff --git a/en/release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md b/en/release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md index e865832eebbb0b34ee233e5974a3757cb74a527e..2d8a2f24d0817d374462a298110a33cfefa7f55e 100644 --- a/en/release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md +++ b/en/release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md @@ -1,6 +1,6 @@ -# JS API Changes of the Utils Subsystem +# JS API Changes of the Compiler and Runtime Subsystem -The table below lists the APIs changes of the Utils subsystem in OpenHarmony 3.2 Beta2 over OpenHarmony 3.2 Beta1. +The table below lists the APIs changes of the compiler and runtime subsystem in OpenHarmony 3.2 Beta2 over OpenHarmony 3.2 Beta1. ## API Changes diff --git a/en/release-notes/api-diff/v3.2-beta3/Readme-EN.md b/en/release-notes/api-diff/v3.2-beta3/Readme-EN.md index caa19c0d47f00a067d0166fe1c59b04a35601899..42a3798286203c9d711723df4d1b1e8f3e1a99aa 100644 --- a/en/release-notes/api-diff/v3.2-beta3/Readme-EN.md +++ b/en/release-notes/api-diff/v3.2-beta3/Readme-EN.md @@ -10,7 +10,7 @@ This directory records the API changes in OpenHarmony 3.2 Beta3 over OpenHarmony - [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) + - [Compiler and runtime 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) diff --git a/en/release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md b/en/release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md index 3c1957aff039872d58115413ad1b216a9ff77424..3510e655cb337008b29c8ecc66b743bf96629ac5 100644 --- a/en/release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md +++ b/en/release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md @@ -1,6 +1,6 @@ -# JS API Changes of the Utils Subsystem +# JS API Changes of the Compiler and Runtime Subsystem -The table below lists the APIs changes of the Utils subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. +The table below lists the APIs changes of the compiler and runtime subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. ## API Changes diff --git a/en/release-notes/api-diff/v3.2-beta4/Readme-EN.md b/en/release-notes/api-diff/v3.2-beta4/Readme-EN.md index 945501b129f35e4e2e6e5ab5ae12e2326eb97dba..e6788c41190e1a5c0d4f6a274e4dd4fb6901a727 100644 --- a/en/release-notes/api-diff/v3.2-beta4/Readme-EN.md +++ b/en/release-notes/api-diff/v3.2-beta4/Readme-EN.md @@ -9,7 +9,7 @@ - [Power management subsystem](js-apidiff-battery.md) - [Bundle management framework](js-apidiff-bundle.md) - [Communication subsystem](js-apidiff-communication.md) - - [Utils subsystem](js-apidiff-compiler-and-runtime.md) + - [Compiler and runtime subsystem](js-apidiff-compiler-and-runtime.md) - [Customization subsystem](js-apidiff-customization.md) - [DFX subsystem](js-apidiff-dfx.md) - [Distributed data management subsystem](js-apidiff-distributed-data.md) diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md index 76b0bf08104a53dfb2d943ae3a860bfc76111dc1..c5f219a9dca53926c131a4bf36e17122e2b47cce 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md @@ -1,9 +1,10 @@ -# Utils Subsystem Changelog +# Common Library Subsystem Changelog -Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.1(MR) has the following API changes in the URL module of the utils subsystem. +Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.1(MR) has the following API changes in the URL module of the common library subsystem. ## cl.commonlibrary.1 URLParams Class Changes -The constructor function of the **URLParams** class in the URL module of the utils subsystem is changed. + +The constructor function of the **URLParams** class in the URL module of the common library subsystem is changed. Specifically, **constructor(init?: string[][] | Record | string | URLSearchParams)** is changed to **constructor(init?: string[][] | Record | string | URLParams)**, and the parameter type is changed from **URLSearchParams** to **URLParams**. @@ -38,7 +39,8 @@ try { } ``` ## cl.commonlibrary.2 URL Attribute Changes of URLParams Class APIs -The URL attributes of the URL module in the utils subsystem are changed. + +The URL attributes of the URL module in the common library subsystem are changed. Specifically, the **searchParams: URLSearchParams** attribute is deprecated, and the **params: URLParams** attribute is added. diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-mediaLibrary.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-mediaLibrary.md new file mode 100644 index 0000000000000000000000000000000000000000..fbb2d0d39e2bb292b2d75164ea30b6b6e1a6c00b --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-mediaLibrary.md @@ -0,0 +1,116 @@ +# File Subsystem Changelog + +## cl.file.1 mediaLibrary APIs Changed + +The **MediaLibrary** class of the multimedia component is replaced by the **FilePicker** class. + +**Change Impact** + +For applications developed based on earlier versions, pay attention to the changes of APIs. **FilePicker** is a system application preset in OpenHarmony. You can use it to select and save files. + +**Key API/Component Changes** + +The APIs of **MediaLibrary**, located in **@ohos.multimedia.medialibrary**, are deprecated. The **FilePicker** class, located in [@ohos.file.picker](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.file.picker.d.ts) is used. + +| Module | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------------------------------------------------ | -------- | +| medialibrary | **function** getMediaLibrary(): MediaLibrary; | Deprecated | +| medialibrary | **function** getMediaLibrary(context: Context): MediaLibrary; | Deprecated | +| medialibrary | **function** getFileAssets(options: MediaFetchOptions, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** getFileAssets(options: MediaFetchOptions): Promise\ | Deprecated | +| medialibrary | **function** on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void | Deprecated | +| medialibrary | **function** off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void | Deprecated | +| medialibrary | **function** createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise\ | Deprecated | +| medialibrary | **function** deleteAsset(uri: string): Promise\ | Deprecated | +| medialibrary | **function** deleteAsset(uri: string, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** getPublicDirectory(type: DirectoryType, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** getPublicDirectory(type: DirectoryType): Promise\ | Deprecated | +| medialibrary | **function** getAlbums(options: MediaFetchOptions, callback: AsyncCallback\\>): void | Deprecated | +| medialibrary | **function** getAlbums(options: MediaFetchOptions): Promise\\> | Deprecated | +| medialibrary | **function** release(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** release(): Promise\ | Deprecated | +| medialibrary | **function** storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** storeMediaAsset(option: MediaAssetOption): Promise\ | Deprecated | +| medialibrary | **function** startImagePreview(images: Array\, index: number, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** startImagePreview(images: Array\, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** startImagePreview(images: Array\, index?: number): Promise\ | Deprecated | +| medialibrary | **function** startMediaSelect(option: MediaSelectOption, callback: AsyncCallback\\>): void | Deprecated | +| medialibrary | **function** startMediaSelect(option: MediaSelectOption): Promise\\> | Deprecated | +| medialibrary | **function** getActivePeers(): Promise\\>; | Deprecated | +| medialibrary | **function** getActivePeers(callback: AsyncCallback\\>): void; | Deprecated | +| medialibrary | **function** getAllPeers(): Promise\\>; | Deprecated | +| medialibrary | **function** FileAsset.isDirectory(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.isDirectory():Promise\ | Deprecated | +| medialibrary | **function** FileAsset.commitModify(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.commitModify(): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.open(mode: string, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.open(mode: string): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.close(fd: number, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.close(fd: number): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.getThumbnail(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.getThumbnail(size: Size, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.getThumbnail(size?: Size): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.favorite(isFavorite: boolean, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.favorite(isFavorite: boolean): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.isFavorite(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.isFavorite():Promise\ | Deprecated | +| medialibrary | **function** FileAsset.trash(isTrash: boolean, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.trash(isTrash: boolean): Promise\ | Deprecated | +| medialibrary | **function** FileAsset.isTrash(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FileAsset.isTrash():Promise\ | Deprecated | +| medialibrary | **function** FetchFileResult.getCount(): number | Deprecated | +| medialibrary | **function** FetchFileResult.isAfterLast(): boolean | Deprecated | +| medialibrary | **function** FetchFileResult.close(): void | Deprecated | +| medialibrary | **function** FetchFileResult.getFirstObject(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FetchFileResult.getFirstObject(): Promise\ | Deprecated | +| medialibrary | **function** FetchFileResult.getNextObject(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FetchFileResult.getNextObject(): Promise\ | Deprecated | +| medialibrary | **function** FetchFileResult.getLastObject(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FetchFileResult.getLastObject(): Promise\ | Deprecated | +| medialibrary | **function** FetchFileResult.getPositionObject(index: number, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** FetchFileResult.getPositionObject(index: number): Promise\ | Deprecated | +| medialibrary | **function** FetchFileResult.getAllObject(callback: AsyncCallback\\>): void | Deprecated | +| medialibrary | **function** FetchFileResult.getAllObject(): Promise\\> | Deprecated | +| medialibrary | **function** Album.commitModify(callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** Album.commitModify(): Promise\ | Deprecated | +| medialibrary | **function** Album.getFileAssets(options: MediaFetchOptions, callback: AsyncCallback\): void | Deprecated | +| medialibrary | **function** Album.getFileAssets(options?: MediaFetchOptions): Promise\ | Deprecated | +| medialibrary | **enum** DeviceType | Deprecated | +| medialibrary | **enum** FileKey | Deprecated | +| medialibrary | **enum** DirectoryType | Deprecated | +| medialibrary | **enum** MediaType | Deprecated | +| medialibrary | **interface** PeerInfo | Deprecated | +| medialibrary | **interface** Size | Deprecated | +| medialibrary | **interface** MediaFetchOptions | Deprecated | +| medialibrary | **interface** MediaAssetOption | Deprecated | +| medialibrary | **interface** MediaSelectOption | Deprecated | +| medialibrary | **interface** FileAsset | Deprecated | + +**Adaptation Guide** + +For example, refer to the code snippet below to call an API to select an image: + +```js +import picker from '@ohos.file.picker'; + +async function example() { + try { + let PhotoSelectOptions = new picker.PhotoSelectOptions(); + PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; + PhotoSelectOptions.maxSelectNumber = 1; + let photoPicker = new picker.PhotoViewPicker(); + photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { + if (PhotoSelectResult !== undefined) { + console.info("PhotoViewPicker.select pass, PhotoSelectResult uri: " + JSON.stringify(PhotoSelectResult)); + } else { + console.error("PhotoViewPicker.select PhotoSelectResult is undefined"); + } + }).catch((err) => { + console.error("PhotoViewPicker.select fail, err: " + err); + }); + } catch (err) { + console.error("PhotoViewPicker fail, err: " + err); + } +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..283f2796178e294f68f755ea2570f7cc1a24a634 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md @@ -0,0 +1,21 @@ +# Resource Scheduler Subsystem Changelog + +## cl.resourceschedule.workScheduler +The data type of the **parameters** attribute value is changed. Specifically, the number, string, and boolean types are supported, but the any type is not. + +**Change Impact** + +For applications developed based on OpenHarmony3.2.10.7 and later SDK versions, the **parameters** attribute value can use the number, string, and boolean types only. If it uses the any type, a compilation error is reported. + +**Key API/Component Changes** + +The **parameters** attribute in @ohos.resourceschedule.workScheduler.d.ts is changed. + +| Class| API Type| Statement Before the Change| Statement After the Change| +| -- | -- | -- | -- | +| workScheduler.WorkInfo | field | parameters?: {[key: string]: any} | parameters?: {[key: string]: number | string | boolean} | + + +**Adaptation Guide** + +The **parameters** attribute uses the {[key: string]: number | string | boolean} data type. diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-telephony.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-telephony.md new file mode 100644 index 0000000000000000000000000000000000000000..e2e631e1f4cdeecd88ba792956e8becc0e0bccab --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-telephony.md @@ -0,0 +1,223 @@ +# Telephony Subsystem Changelog + + + +## cl.telephony.1 Call Module reject API Change +Changed the `reject` API to the `rejectCall` API in the call module of the telephony subsystem since API version 9. + +You need to adapt your application. + +**Change Impact** + +The `reject` API is deprecated and cannot be used any more. Use the `rejectCall` API instead. Otherwise, relevant functions will be affected. + +- Involved APIs: + +```js + function reject(callId: number, callback: AsyncCallback): void; + function reject(callId: number, options: RejectMessageOptions, callback: AsyncCallback): void; + function reject(callId?: number, options?: RejectMessageOptions): Promise; + function reject(callback: AsyncCallback): void; + function reject(options: RejectMessageOptions, callback: AsyncCallback): void; +``` + +- Before change: + +```js + function reject(callId: number, callback: AsyncCallback): void; + function reject(callId: number, options: RejectMessageOptions, callback: AsyncCallback): void; + function reject(callId?: number, options?: RejectMessageOptions): Promise; + function reject(callback: AsyncCallback): void; + function reject(options: RejectMessageOptions, callback: AsyncCallback): void; +``` + +- After change: + +```js + function rejectCall(callId: number, callback: AsyncCallback): void; + function rejectCall(callId: number, options: RejectMessageOptions, callback: AsyncCallback): void; + function rejectCall(callId?: number, options?: RejectMessageOptions): Promise; + function rejectCall(callback: AsyncCallback): void; + function rejectCall(options: RejectMessageOptions, callback: AsyncCallback): void; +``` + + +**Adaptation Guide** + +The `reject` API is deprecated and cannot be used any more. Use the `rejectCall` API instead. +Use the new API. The sample code is as follows: + +```js +call.rejectCall("138xxxxxxxx", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +let promise = call.rejectCall(1, rejectMessageOptions); +promise.then(data => { + console.log(`rejectCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +let promise = call.rejectCall(1, rejectMessageOptions); +promise.then(data => { + console.log(`rejectCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +```js +call.rejectCall((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.rejectCall(rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## cl.telephony.2 Call Module answer API Change +Changed the `answer` API to the `answerCall` API in the call module of the telephony subsystem since API version 9. + +You need to adapt your application. + +**Change Impact** + +The `answer` API is deprecated and cannot be used any more. Use the `answerCall` API instead. Otherwise, relevant functions will be affected. + +- Involved APIs: + +```js + function answer(callId: number, callback: AsyncCallback): void; + function answer(callId?: number): Promise; + function answer(callback: AsyncCallback): void; +``` + +- Before change: + +```js + function answer(callId: number, callback: AsyncCallback): void; + function answer(callId?: number): Promise; + function answer(callback: AsyncCallback): void; +``` + +- After change: + +```js + function answerCall(callId: number, callback: AsyncCallback): void; + function answerCall(callId?: number): Promise; + function answerCall(callback: AsyncCallback): void; +``` + + +**Adaptation Guide** + +The `answer` API is deprecated and cannot be used any more. Use the `answerCall` API instead. +Use the new API. The sample code is as follows: + +```js +call.answerCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +```js +let promise = call.answerCall(1); +promise.then(data => { + console.log(`answerCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`answerCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +```js +call.answerCall((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## cl.telephony.1 Call Module hangup API Change +Changed the `hangup` API to the `hangUpCall` API in the call module of the telephony subsystem since API version 9. + +You need to adapt your application. + +**Change Impact** + +The `hangup` API is deprecated and cannot be used any more. Use the `hangUpCall` API instead. Otherwise, relevant functions will be affected. + +- Involved APIs: + +```js + function hangup(callId: number, callback: AsyncCallback): void; + function hangup(callId?: number): Promise; + function hangup(callback: AsyncCallback): void; +``` + +- Before change: + +```js + function hangup(callId: number, callback: AsyncCallback): void; + function hangup(callId?: number): Promise; + function hangup(callback: AsyncCallback): void; +``` + +- After change: + +```js + function hangUpCall(callId: number, callback: AsyncCallback): void; + function hangUpCall(callId?: number): Promise; + function hangUpCall(callback: AsyncCallback): void; +``` + + +**Adaptation Guide** + +The `hangup` API is deprecated and cannot be used any more. Use the `hangUpCall` API instead. +Use the new API. The sample code is as follows: + +```js +call.hangUpCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +```js +let promise = call.hangUpCall(1); +promise.then(data => { + console.log(`hangUpCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`hangUpCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +```js +call.hangUpCall((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md index 39c327d863b2e322ece336edf983f053e451d398..6ebe3fe1b7988aab988b1b93cdf1664378665304 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md @@ -1,4 +1,4 @@ -# Ability Subsystem Changelog +# Ability Framework Changelog ## cl.ability.1 AreaMode APIs Changed Duplicate **AreaMode** APIs are deleted. @@ -106,3 +106,163 @@ let context: common.UIAbilityContext = globalThis.abilityContext; let appContext = context.getApplicationContext(); appContext.getRunningProcessInformation() ``` + + + +## cl.ability.4 WantConstant.Flags API Change + +**WantConstant.Flags** has multiple invalid flag definitions. These invalid flags are deleted. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_FORWARD_RESULT | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CONTINUATION | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_NOT_OHOS_COMPONENT | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_FORM_ENABLED | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_AUTH_PERSISTABLE_URI_PERMISSION | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_AUTH_PREFIX_URI_PERMISSION | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITYSLICE_MULTI_DEVICE | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_START_FOREGROUND_ABILITY | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CONTINUATION_REVERSIBLE | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_INSTALL_WITH_BACKGROUND_MODE | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CLEAR_MISSION | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_NEW_MISSION | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_MISSION_TOP | Deleted | + + + +## cl.ability.5 WantConstant.Action API Change + +**WantConstant.Action** has multiple invalid action definitions. These invalid actions are deleted. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_APP_ACCOUNT_AUTH | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_MARKET_DOWNLOAD | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_MARKET_CROWDTEST | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_SANDBOX | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_BUNDLE_NAME | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_MODULE_NAME | Deleted | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_ABILITY_NAME | Deleted | + + + +## cl.ability.6 Caller APIs Changed + +Caller APIs use the **Parcelable** and **MessageSequence** objects provided by RPC in API version 9 to replace the deprecated **Sequenceable** and **MessageParcel** object. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| api/@ohos.app.ability.UIAbility.d.ts | CalleeCallback | (indata: rpc.MessageParcel): rpc.Sequenceable; | Changed to **(indata: rpc.MessageSequence): rpc.Parcelable;**. | +| api/@ohos.app.ability.UIAbility.d.ts | Caller | call(method: string, data: rpc.Sequenceable): Promise; | Changed to **call(method: string, data: rpc.Parcelable): Promise;**. | +| api/@ohos.app.ability.UIAbility.d.ts | Caller | callWithResult(method: string, data: rpc.Sequenceable): Promise; | Changed to **callWithResult(method: string, data: rpc.Parcelable): Promise;**. | + +**Adaptation Guide** + +The following illustrates how to call the caller APIs in your application. + +Code before the change: + +```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + let method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readSequenceable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } +``` + +Code after the change: + +```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + let method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readParcelable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-util.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-util.md new file mode 100644 index 0000000000000000000000000000000000000000..52035aa2be49e1f11d72e91ec65f413112f5f13a --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-util.md @@ -0,0 +1,99 @@ +# Util Subsystem Changelog + +Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.7(MR) has the following API changes in the util subsystem. + +## cl.util.1. randomUUID Name Changed +The **randomUUID** function name is changed to **generateRandomUUID**. + +Before change: function randomUUID(entropyCache?: boolean): string
After change: function generateRandomUUID(entropyCache?: boolean): string + +You need to adapt your application. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Method/Attribute/Enum/Constant | Change Type| +| :---------- | ------------------- | ------- | +| @ohos.util | function randomUUID(entropyCache?: boolean): string | Deleted | +| @ohos.util | function generateRandomUUID(entropyCache?: boolean): string| Added | + +**Adaptation Guide** + +Refer to the code snippet below to call **generateRandomUUID** in your application. + +Example: + +```ts +import util from '@ohos.util' +let uuid = util.generateRandomUUID(true); +console.log("RFC 4122 Version 4 UUID:" + uuid); +// Output: +// RFC 4122 Version 4 UUID:88368f2a-d5db-47d8-a05f-534fab0a0045 +``` + +## cl.util.2 randomBinaryUUID Name Changed +The **randomBinaryUUID** function name is changed to **generateRandomBinaryUUID**. + +Before change: function randomBinaryUUID(entropyCache?: boolean): Uint8Array
After change: function generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array + +You need to adapt your application. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Method/Attribute/Enum/Constant | Change Type| +| :---------- | ------------------- | ------- | +| @ohos.util | function randomBinaryUUID(entropyCache?: boolean): Uint8Array; | Deleted | +| @ohos.util | function generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array| Added | + +**Adaptation Guide** + +Refer to the code snippet below to call **generateRandomBinaryUUID** in your application. + +Example: + +```ts +import util from '@ohos.util' +let uuid = util.generateRandomBinaryUUID(true); +console.log(JSON.stringify(uuid)); +// Output: +// 138,188,43,243,62,254,70,119,130,20,235,222,199,164,140,150 +``` + +## cl.util.3. contains Parameter Type in the LRUCache Class Changed +The **contains** parameter type in the LRUCache class is changed from **object** to **K**. + +Before change: contains(key: object): boolean
After change: contains(key: K): boolean + +You need to adapt your application. + +**Change Impact** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| :-------- | ---------| -------------------------------- | -------- | +| @ohos.util | LRUCache | contains(key: object): boolean | Deleted | +| @ohos.util | LRUCache | contains(key: K): boolean | Added | + +**Adaptation Guide** + +Follow the code snippet to use the **contains** function in your application. + +Example: + +```ts +import util from '@ohos.util' +let pro = new util.LRUCache(); +pro.put(2,10); +let obj = {1:"key"}; +let result = pro.contains(obj); +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-account_os_account.md b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-account_os_account.md new file mode 100644 index 0000000000000000000000000000000000000000..8678507b6c8d8449e8cac47e6b8669611865bec2 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-account_os_account.md @@ -0,0 +1,391 @@ +# Account Subsystem Changelog + +OpenHarmony 4.0.3.2 has the following changes in account module APIs: + +## cl.account_os_account.1 App Account API isAccountRemovable Renamed + +Changed **isAccountRemovable** in the **Authenticator** class to **checkAccountRemovable**. + +**Change Impact** + +The **isAccountRemovable** API in the **Authenticator** class cannot be used from 4.0.3.2. Use **checkAccountRemovable** instead. + +**Key API/Component Changes** + +- Involved APIs: + ```ts + class Authenticator { + ... + isAccountRemovable + ... + } + ``` +- Before change: + + ```ts + class Authenticator { + ... + /** + * Checks whether the specified account can be removed. + * @param name Indicates the account name. + * @param callback Indicates the authenticator callback. + * @returns void. + * @since 9 + */ + isAccountRemovable(name: string, callback: AuthCallback): void; + ... + } + ``` + +- After change: + + ```ts + class Authenticator { + ... + /** + * Checks whether the specified account can be removed. + * @param name Indicates the account name. + * @param callback Indicates the authenticator callback. + * @returns void. + * @since 9 + */ + checkAccountRemovable(name: string, callback: AuthCallback): void; + ... + } + ``` + +## cl.account_os_account.2 OS Account API checkConstraintEnabled Renamed + +Changed **checkConstraintEnabled** to **checkOsAccountConstraintEnabled**. + +**Change Impact** + +The **checkConstraintEnabled** API cannot be used from 4.0.3.2. Use **checkOsAccountConstraintEnabled** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + checkConstraintEnabled + ... +} +``` + +- Before change: + + ```ts + checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback): void; + checkConstraintEnabled(localId: number, constraint: string): Promise; + ``` + +- After change: + + ```ts + checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback): void; + checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise; + ``` + +## cl.account_os_account.3 OS Account API **checkOsAccountConstraintEnabled** Permission Scenario Change + +Added an optional permission **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** to the **checkOsAccountConstraintEnabled** API. + +**Change Impact** + +In 4.0.3.2 and later versions, an app with the **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** permission can also call **checkOsAccountConstraintEnabled**. +The use of **ohos.permission.MANAGE_LOCAL_ACCOUNTS** is not affected. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + checkOsAccountConstraintEnabled + ... +} +``` + +- Before change: + + ```ts + ... + * @permission ohos.permission.MANAGE_LOCAL_ACCOUNTS + ... + checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback): void; + checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise; + ``` + +- After change: + + ```ts + ... + * @permission ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + ... + checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback): void; + checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise; + ``` + +## cl.account_os_account.4 OS Account API queryOsAccountLocalIdFromProcessd Renamed + +Changed **queryOsAccountLocalIdFromProcess** to **getOsAccountLocalId**. + +**Change Impact** + +The **queryOsAccountLocalIdFromProcess** API cannot be used from 4.0.3.2. Use **getOsAccountLocalId** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + queryOsAccountLocalIdFromProcess + ... +} +``` +- Before change: + + ```ts + queryOsAccountLocalIdFromProcess(callback: AsyncCallback): void; + queryOsAccountLocalIdFromProcess(): Promise; + ``` + +- After change: + + ```ts + getOsAccountLocalId(callback: AsyncCallback): void; + getOsAccountLocalId(): Promise; + ``` + +## cl.account_os_account.5 OS Account API queryOsAccountLocalIdFromUid Renamed + +Changed **queryOsAccountLocalIdFromUid** to **getOsAccountLocalIdForUid**. + +**Change Impact** + +The **queryOsAccountLocalIdFromUid** API cannot be used from 4.0.3.2. Use **getOsAccountLocalIdForUid** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + queryOsAccountLocalIdFromUid + ... +} +``` + +- Before change: + + ```ts + queryOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback): void; + queryOsAccountLocalIdFromUid(uid: number): Promise; + ``` + +- After change: + + ```ts + getOsAccountLocalIdForUid(uid: number, callback: AsyncCallback): void; + getOsAccountLocalIdForUid(uid: number): Promise; + ``` + +## cl.account_os_account.6 OS Account API queryOsAccountLocalIdFromDomain Renamed + +Changed **queryOsAccountLocalIdFromDomain** to **getOsAccountLocalIdForDomain**. + +**Change Impact** + +The **queryOsAccountLocalIdFromDomain** API cannot be used from 4.0.3.2. Use **getOsAccountLocalIdForDomain** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + queryOsAccountLocalIdFromDomain + ... +} +``` + +- Before change: + + ```ts + queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback): void; + queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise; + ``` + +- After change: + + ```ts + getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback): void; + getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise; + ``` + +## cl.account_os_account.7 OS Account API getActivatedOsAccountIds Renamed + +Changed **getActivatedOsAccountIds** to **getActivatedOsAccountLocalIds**. + +**Change Impact** + +The **getActivatedOsAccountIds** API cannot be used from 4.0.3.2. Use **getActivatedOsAccountLocalIds** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + getActivatedOsAccountIds + ... +} +``` + +- Before change: + + ```ts + getActivatedOsAccountIds(callback: AsyncCallback>): void; + getActivatedOsAccountIds(): Promise>; + ``` + +- After change: + + ```ts + getActivatedOsAccountLocalIds(callback: AsyncCallback>): void; + getActivatedOsAccountLocalIds(): Promise>; + ``` + +## cl.account_os_account.8 OS Account API queryOsAccountLocalIdBySerialNumber Renamed + +Changed **queryOsAccountLocalIdBySerialNumber** to **getOsAccountLocalIdForSerialNumber**. + +**Change Impact** + +The **queryOsAccountLocalIdBySerialNumber** API cannot be used from 4.0.3.2. Use **getOsAccountLocalIdForSerialNumber** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + queryOsAccountLocalIdBySerialNumber + ... +} +``` + +- Before change: + + ```ts + queryOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback): void; + queryOsAccountLocalIdBySerialNumber(serialNumber: number): Promise; + ``` + +- After change: + + ```ts + getOsAccountLocalIdForSerialNumber(serialNumber: number, callback: AsyncCallback): void; + getOsAccountLocalIdForSerialNumber(serialNumber: number): Promise; + ``` + +## cl.account_os_account.9 OS Account API querySerialNumberByOsAccountLocalId Renamed + +Changed **querySerialNumberByOsAccountLocalId** to **getSerialNumberForOsAccountLocalId**. + +**Change Impact** + +The **querySerialNumberByOsAccountLocalId** API cannot be used from 4.0.3.2. Use **getSerialNumberForOsAccountLocalId** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + querySerialNumberByOsAccountLocalId + ... +} +``` + +- Before change: + + ```ts + querySerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback): void; + querySerialNumberByOsAccountLocalId(localId: number): Promise; + ``` + +- After change: + + ```ts + getSerialNumberForOsAccountLocalId(localId: number, callback: AsyncCallback): void; + getSerialNumberForOsAccountLocalId(localId: number): Promise; + ``` + +## cl.account_os_account.10 OS Account API getBundleIdFromUid Renamed + +Changed **getBundleIdFromUid** to **getBundleIdForUid**. + +**Change Impact** + +The **getBundleIdFromUid** API cannot be used from 4.0.3.2. Use **getBundleIdForUid** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + getBundleIdFromUid + ... +} +``` + +- Before change: + + ```ts + getBundleIdFromUid(uid: number, callback: AsyncCallback): void; + getBundleIdFromUid(uid: number): Promise; + ``` + +- After change: + + ```ts + getBundleIdForUid(uid: number, callback: AsyncCallback): void; + getBundleIdForUid(uid: number): Promise; + ``` + +## cl.account_os_account.11 OS Account API queryOsAccountConstraintSourceTypes Renamed + +Changed **queryOsAccountConstraintSourceTypes** to **getOsAccountConstraintSourceTypes**. + +**Change Impact** + +The **queryOsAccountConstraintSourceTypes** API cannot be used from 4.0.3.2. Use **getOsAccountConstraintSourceTypes** instead. + +**Key API/Component Changes** + +- Involved APIs: +``` +interface AccountManager { + ... + queryOsAccountConstraintSourceTypes + ... +} +``` + +- Before change: + + ```ts + queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback>): void; + queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise>; + ``` + +- After change: + + ```ts + getOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback>): void; + getOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise>; + ``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-pasteboard.md b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-pasteboard.md new file mode 100644 index 0000000000000000000000000000000000000000..8d8b439cc3a7461162c51abc2f84d09f00412e3d --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-pasteboard.md @@ -0,0 +1,66 @@ +# Pasteboard Subsystem Changelog + +OpenHarmony 4.0.3.2 has the following changes in the APIs of the pasteboard subsystem: + +## cl.pasteboard.1 convertToTextV9 API Change + +Renamed **convertToTextV9** **toPlainText()** and changed the API from asynchronous to synchronous. + +**Change Impact** + +Applications developed using the **convertToTextV9** API in versions earlier than OpenHarmony 4.0.3.3 cannot be used in OpenHarmony 4.0.3.3 and later versions. + +**Key API/Component Changes** + +- Involved APIs: + + function convertToTextV9 + +- Before change: + + ```ts + convertToTextV9(callback: AsyncCallback): void; + convertToTextV9(): Promise; + ``` + +- After change: + + ```ts + toPlainText(): string; + ``` + + +**Adaptation Guide** + +Replace **convertToTextV9**, an asynchronous API, with **toPlainText**, a synchronous API. + +## cl.pasteboard.2 ShareOption Enum Name Change + +Changed the enum names of **ShareOption** from UpperCamelCase to all caps. + +**Change Impact** + +Applications developed using the **InApp/LocalDevice/CrossDevice** attributes in versions earlier than OpenHarmony 4.0.3.3 cannot be used in OpenHarmony 4.0.3.3 and later versions. + +**Key API/Component Changes** + +ShareOption9+ + +Before change: +| Name| Value| Description | +| ---- |---|-------------------| +| InApp | 0 | Only intra-application pasting is allowed. | +| LocalDevice | 1 | Paste is allowed in any application on the local device.| +| CrossDevice | 2 | Paste is allowed in any application across devices. | + + +After change: +| Name| Value| Description | +| ---- |---|-------------------| +| INAPP | 0 | Only intra-application pasting is allowed. | +| LOCALDEVICE | 1 | Paste is allowed in any application on the local device.| +| CROSSDEVICE | 2 | Paste is allowed in any application across devices. | + +**Adaptation Guide** + +Perform adaptation based on the new semantics. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-power.md b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-power.md new file mode 100644 index 0000000000000000000000000000000000000000..c4506242ea6b189ec9a403e0b5ce85d2490f1b34 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-power.md @@ -0,0 +1,82 @@ +# Power Subsystem Changelog + +## cl.powermgr.1 CommonEventBatteryChangedCode API Change + +Changed the **CommonEventBatteryChangedCode** enum class in [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) as follows: + +- Changed the class name to **CommonEventBatteryChangedKey**. +- Deleted **EXTRA_MAX_CURRENT**, **EXTRA_MAX_VOLTAGE**, and **EXTRA_CHARGE_COUNTER**. +- Changed the enum value type from numeric to string. + +#### Change Impact + +The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected. + +#### Key API/Component Changes + +Before change: + +| Name | Value | Description | +| -------------------- | ---- | -------------------------------------------------- | +| EXTRA_SOC | 0 | Remaining battery level in percentage. | +| EXTRA_VOLTAGE | 1 | Battery voltage of the device. | +| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. | +| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. | +| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. | +| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. | +| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. | +| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. | +| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. | +| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.| +| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. | +| EXTRA_CAPACITY_LEVEL | 11 | Battery level of the device. | + +After change: + +| Name | Value | Description | +| -------------------- | --------------- | -------------------------------------------------- | +| EXTRA_SOC | "soc" | Remaining battery level in percentage. | +| EXTRA_CHARGE_STATE | "chargeState" | Battery charging status of the device. | +| EXTRA_HEALTH_STATE | "healthState" | Battery health status of the device. | +| EXTRA_PLUGGED_TYPE | "pluggedType" | Type of the charger connected to the device. | +| EXTRA_VOLTAGE | "voltage" | Battery voltage of the device. | +| EXTRA_TECHNOLOGY | "technology" | Battery technology of the device. | +| EXTRA_TEMPERATURE | "temperature" | Battery temperature of the device. | +| EXTRA_PRESENT | "present" | Whether the battery is supported by the device or installed.| +| EXTRA_CAPACITY_LEVEL | "capacityLevel" | Battery level of the device. | + +#### Adaptation Guide + +For details, see the API reference of the [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) API. +## cl.powermgr.2 estimatedRemainingChargeTime API Change + +Changed the **estimatedRemainingChargeTime** API in [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) to a system API. + +#### Change Impact + +The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected. + +#### Adaptation Guide + +For details, see the API reference of the [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) API. + +## cl.powermgr.3 System Common Event Behavior Change + +The following common events are provided in the battery information through [@ohos.commonEventManager (common event module)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-commonEventManager.md): + +- COMMON_EVENT_BATTERY_LOW: common event for low battery level. It includes the remaining battery in percentage. +- COMMON_EVENT_BATTERY_OKAY: common event for normal battery level. It includes the remaining battery in percentage. +- COMMON_EVENT_POWER_CONNECTED: common event for connection to an external power supply. It includes the type of the power supply to which the device is connected. +- COMMON_EVENT_POWER_DISCONNECTED: common event for disconnection from an external power supply. It includes the type of the power supply from which the device is disconnected. +- COMMON_EVENT_CHARGING: common event for starting of battery charging. It includes the battery charging status. +- COMMON_EVENT_DISCHARGING: common event for ending of battery charging. It includes the battery charging status. + +Changed the method of obtaining data from common events from **CommonEventData.data** to **CommonEventData.code**. + +#### Change Impact + +The application developed based on earlier versions needs to adapt the method for obtaining common events in the battery information. Otherwise, the original service logic will be affected. + +#### Adaptation Guide + +For details, see the API reference of the [@ohos.commonEventManager (Common Event Manager)](../../../application-dev/reference/apis/js-apis-commonEventManager.md) API. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-sensor.md b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..7a2e2946d69a0f116616152cd82eb8a2bae96c58 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.3.2/changelogs-sensor.md @@ -0,0 +1,49 @@ +# Pan-sensor Subsystem Changelog + +## cl.ability.1 Attribute Name Changed from venderName to vendorName in the Sensor API + +**venderName** is changed to **vendorName**. + +**Change Impact** + +The **venderName** attribute cannot be used anymore. Use **vendorName** instead. + +**Key API/Component Changes** + +- Before change: + +```js + interface Sensor { + sensorName:string; /**< Sensor name */ + venderName:string; /**< Sensor vendor version */ + firmwareVersion:string; /**< Sensor firmware version */ + hardwareVersion:string; /**< Sensor hardware version */ + sensorId:number; /**< Sensor type ID, {@code SensorType} */ + maxRange:number; /**< Maximum measurement range of the sensor */ + minSamplePeriod:number; /**< Minimum sample period allowed, in ns */ + maxSamplePeriod:number; /**< maximum sample period allowed, in ns */ + precision:number; /**< Sensor accuracy */ + power:number; /**< Sensor power */ + } +``` + +- After change: + +```js + interface Sensor { + sensorName:string; /**< Sensor name */ + vendorName:string; /**< Sensor vendor version */ + firmwareVersion:string; /**< Sensor firmware version */ + hardwareVersion:string; /**< Sensor hardware version */ + sensorId:number; /**< Sensor type ID, {@code SensorType} */ + maxRange:number; /**< Maximum measurement range of the sensor */ + minSamplePeriod:number; /**< Minimum sample period allowed, in ns */ + maxSamplePeriod:number; /**< maximum sample period allowed, in ns */ + precision:number; /**< Sensor accuracy */ + power:number; /**< Sensor power */ + } +``` + +**Adaptation Guide** + +Replace **venderName** with **vendorName**. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..225ac70d1f4e080f5d83f0bcb768a9afbbc03e1f --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md @@ -0,0 +1,32 @@ +# Resource Scheduler Subsystem Changelog + +## cl.resourceschedule.workScheduler + +The WorkSchedulerExtensionAbility provides a default WorkSchedulerExtensionContext. + +**Change Impact** + +Applications developed based on OpenHarmony4.0.5.1 and later SDK versions can use the default context attribute as the context environment of a WorkSchedulerExtension. + +**Key API/Component Changes** + +The context attribute is added to **@ohos.WorkSchedulerExtensionAbility.d.ts**. The **application/WorkSchedulerExtensionContext.d.ts** file is added, which is inherited from ExtensionContext. + +| Module| Class| Method/Attribute/Enum/Constant| Change Type| +| -- | -- | -- | -- | +| @ohos.WorkSchedulerExtensionAbility.d.ts | WorkSchedulerExtensionAbility | context: WorkSchedulerExtensionContext; | Added| +| application/WorkSchedulerExtensionContext.d.ts | WorkSchedulerExtensionContext | - | Added| + +**Adaptation Guide** + +The context is obtained through a WorkSchedulerExtensionAbility child class instance. + +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + +class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext. + } +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-miscdevice.md b/en/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-miscdevice.md new file mode 100644 index 0000000000000000000000000000000000000000..100975f0aec6f581d517b3b2d0ee0e598de4388e --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-miscdevice.md @@ -0,0 +1,94 @@ +# Pan-sensor Subsystem Changelog + +## cl.vibrator Added isSupportEffect + +The **isSupportEffect** API is added. + +**Change Impact** + +Applications developed based on OpenHarmony4.0.5.2 or a later SDK version can use **isSupportEffect** to check whether the passed effect ID is supported. + +**Key API/Component Changes** + +The **isSupportEffect** API is added in **@ohos.vibrator.d.ts**. + +| Module| Class| Method/Attribute/Enum/Constant| Change Type| +| -- | -- | -- | -- | +| @ohos.vibrator.d.ts | vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Added| +| @ohos.vibrator.d.ts | vibrator | isSupportEffect(effectId: string): Promise<boolean> | Added| + +**Adaptation Guide** + +Call **isSupportEffect** to check whether the passed effect ID is supported. + +```ts +import vibrator from '@ohos.vibrator'; +try { + // Check whether 'haptic.clock.timer' is supported. + vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { + if (err) { + console.error('isSupportEffect failed, error:' + JSON.stringify(err)); + return; + } + console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); + if (state) { + try { + vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission. + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }, (error) => { + if(error) { + console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error)); + } else { + console.log('haptic.clock.timer vibrator success'); + } + }); + } catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); + } + } + }) +} catch (error) { + console.error('Exception in, error:' + JSON.stringify(error)); +} +``` + +## cl.vibrator Added stopVibration + +The **stopVibration** API is added. + +**Change Impact** + +Applications developed based on OpenHarmony4.0.5.2 or a later SDK version can use **stopVibration** to stop vibration in all modes. + +**Key API/Component Changes** + +The **stopVibration** API is added in **@ohos.vibrator.d.ts**. + +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| ------------------- | -------- | -------------------------------------------------------- | -------- | +| @ohos.vibrator.d.ts | vibrator | stopVibration(callback: AsyncCallback<void>): void | Added | +| @ohos.vibrator.d.ts | vibrator | stopVibration(): Promise<void> | Added | + +**Adaptation Guide** + +Call **stopVibration** to stop vibration in all modes. + +```ts +import vibrator from '@ohos.vibrator'; +try { + // Stop vibration in all modes. + vibrator.stopVibration(function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + return; + } + console.log('Callback returned to indicate successful.'); + }) +} catch (error) { + console.info('errCode: ' + error.code + ' ,msg: ' + error.message); +} +``` diff --git a/en/website.md b/en/website.md index 2431b867aafb1669ef739c1c3d2884fe32223596..c89534497929cd5975debbf051874a1c0c4bbca6 100644 --- a/en/website.md +++ b/en/website.md @@ -43,7 +43,7 @@ - [Power management subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-battery.md) - [Bundle management framework](release-notes/api-diff/v3.2-beta4/js-apidiff-bundle.md) - [Communication subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-communication.md) - - [Utils subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-compiler-and-runtime.md) + - [Compiler and runtime subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-compiler-and-runtime.md) - [Communication subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-customization.md) - [DFX subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-dfx.md) - [Distributed data management subsystem](release-notes/api-diff/v3.2-beta4/js-apidiff-distributed-data.md) @@ -76,7 +76,7 @@ - [Power management subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-battery.md) - [Bundle management framework](release-notes/api-diff/v3.2-beta3/js-apidiff-bundle.md) - [Communication subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-communicate.md) - - [Utils subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md) + - [Compiler and runtime subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-compiler-and-runtime.md) - [DFX subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-dfx.md) - [Distributed data management subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-distributed-data.md) - [Distributed hardware subsystem](release-notes/api-diff/v3.2-beta3/js-apidiff-distributed-hardware.md) @@ -105,7 +105,7 @@ - [ArkUI development framework](release-notes/api-diff/v3.2-beta2/js-apidiff-arkui.md) - [Bundle management framework](release-notes/api-diff/v3.2-beta2/js-apidiff-bundle.md) - [Communication subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-communicate.md) - - [Utils subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md) + - [Compiler and runtime subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-compiler-and-runtime.md) - [DFX subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-dfx.md) - [Distributed data management subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-distributed-data.md) - [Common event and notification subsystem](release-notes/api-diff/v3.2-beta2/js-apidiff-event-and-notification.md) @@ -159,7 +159,7 @@ - [Power management subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-battery.md) - [Bundle management subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-bundle.md) - [Communication subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-communicate.md) - - [Multi-language Runtime subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md) + - [Compiler and runtime subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-compiler-and-runtime.md) - [DFX subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-dfx.md) - [Distributed data management subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-distributed-data.md) - [Distributed hardware subsystem](release-notes/api-diff/v3.1-Release/js-apidiff-distributed-hardware.md) diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index 603a38b9ac205ab36eec595899f2a66afe409565..b81af1f250ccdf126e45ebeccc44f7c29c02a975 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -17,7 +17,6 @@ - 应用程序包结构 - [Stage模型应用程序包结构](quick-start/application-package-structure-stage.md) - [FA模型应用程序包结构](quick-start/application-package-structure-fa.md) - - [HAR包结构](quick-start/har-structure.md) - 应用程序包多HAP机制 - [多HAP机制设计目标](quick-start/multi-hap-objective.md) - [多HAP构建视图](quick-start/multi-hap-build-view.md) @@ -26,11 +25,11 @@ - [多HAP运行机制及数据通信方式](quick-start/multi-hap-principles.md) - [应用程序包安装和卸载流程](quick-start/application-package-install-uninstall.md) - 共享包 + - [共享包概述](quick-start/shared-guide.md) - [HAR](quick-start/har-package.md) - HSP - - [HSP概述](quick-start/hsp-guide.md) - [应用内HSP开发指导](quick-start/in-app-hsp.md) - - [应用间HSP开发指导](quick-start/cross-app-hsp.md) + - [应用间HSP开发指导(仅对系统应用开放)](quick-start/cross-app-hsp.md) - 应用配置文件(Stage模型) - [应用配置文件概述(Stage模型)](quick-start/application-configuration-file-overview-stage.md) - [app.json5配置文件](quick-start/app-configuration-file.md) diff --git a/zh-cn/application-dev/ability-deprecated/context-userguide.md b/zh-cn/application-dev/ability-deprecated/context-userguide.md index d0f51a6da81241bdea8715cb14d642825e9a12f3..baf0f1885ebbcf2119171324e45170a0a3a9cfb6 100644 --- a/zh-cn/application-dev/ability-deprecated/context-userguide.md +++ b/zh-cn/application-dev/ability-deprecated/context-userguide.md @@ -249,9 +249,9 @@ Stage模型下,在Ability的`onWindowStageCreate`生命周期中,可以通 在ArkTS页面中通过以下全局方法获取当前页面关联的Context。 -| 接口名 | 描述 | -| :------------------------------------ | :--------------------------- | -| getContext(component: Object): Object | 获取页面中component所关联的Context对象。 | +| 接口名 | 描述 | +| :------------------------------------ | :----------------------------------------------------------- | +| getContext(component: Object): Object | 获取页面中component所关联的Context对象。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **示例** diff --git a/zh-cn/application-dev/application-dev-guide-for-gitee.md b/zh-cn/application-dev/application-dev-guide-for-gitee.md index 21267735bd801a4e6bfdd366699a584659c43e4c..b8320cd4c830d9fbcd6e012ce54dbfcf34c3248c 100644 --- a/zh-cn/application-dev/application-dev-guide-for-gitee.md +++ b/zh-cn/application-dev/application-dev-guide-for-gitee.md @@ -40,6 +40,8 @@ - [应用测试](application-test/Readme-CN.md) - [IDL工具规格及使用说明书](IDL/idl-guidelines.md) - [Native API的相关指导](napi/Readme-CN.md) +- [文件管理](file-management/medialibrary-overview.md) +- [一次开发,多端部署](key-features/multi-device-app-dev/foreword.md) ### 工具 diff --git a/zh-cn/application-dev/application-dev-guide.md b/zh-cn/application-dev/application-dev-guide.md index 2942726a14e480b66b3bbfb839a892fb4c97cf76..15439726df413f25a8d3612e0b10ca9868ca322c 100644 --- a/zh-cn/application-dev/application-dev-guide.md +++ b/zh-cn/application-dev/application-dev-guide.md @@ -40,6 +40,8 @@ - [应用测试](application-test/arkxtest-guidelines.md) - [IDL工具规格及使用说明书](IDL/idl-guidelines.md) - [Native API的相关指导](napi/napi-guidelines.md) +- [文件管理](file-management/medialibrary-overview.md) +- [一次开发,多端部署](key-features/multi-device-app-dev/foreword.md) ### 工具 diff --git a/zh-cn/application-dev/application-models/Readme-CN.md b/zh-cn/application-dev/application-models/Readme-CN.md index c2ac35df6796f6e01d001115796789d944a8701a..3c05dfc73ae46d173a51979c963d1f13fefb64e1 100644 --- a/zh-cn/application-dev/application-models/Readme-CN.md +++ b/zh-cn/application-dev/application-models/Readme-CN.md @@ -19,7 +19,6 @@ - [ServiceExtensionAbility](serviceextensionability.md) - [DataShareExtensionAbility(仅对系统应用开放)](datashareextensionability.md) - [FormExtensionAbility(服务卡片)](widget-development-stage.md) - - [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) @@ -43,9 +42,12 @@ - [进程模型](process-model-stage.md) - 公共事件 - [公共事件简介](common-event-overview.md) - - [公共事件订阅](common-event-subscription.md) + - 公共事件订阅 + - [公共事件订阅概述](common-event-subscription-overview.md) + - [动态订阅公共事件](common-event-subscription.md) + - [静态订阅公共事件(仅对系统应用开放)](common-event-static-subscription.md) + - [取消动态订阅公共事件](common-event-unsubscription.md) - [公共事件发布](common-event-publish.md) - - [公共事件取消订阅](common-event-unsubscription.md) - [后台服务](background-services.md) - 线程间通信 - [线程模型](thread-model-stage.md) diff --git a/zh-cn/application-dev/application-models/common-event-overview.md b/zh-cn/application-dev/application-models/common-event-overview.md index b83db2e52a1a84075866bb892dc63a67d0c78d06..2872dc9e07423dca819c7dc62d959e08585927ce 100644 --- a/zh-cn/application-dev/application-models/common-event-overview.md +++ b/zh-cn/application-dev/application-models/common-event-overview.md @@ -15,11 +15,11 @@ OpenHarmony通过CES(Common Event Service,公共事件服务)为应用程 公共事件按发送方式可分为:无序公共事件、有序公共事件和粘性公共事件。 -- 无序公共事件:CES转发公共事件时,不考虑订阅者是否接收到,按订阅者订阅先后顺序转发。 +- 无序公共事件:CES转发公共事件时,不考虑订阅者是否接收到,且订阅者接收到的顺序与其订阅顺序无关。 -- 有序公共事件:CES转发公共事件时,按订阅者订阅先后顺序,在接收到前一个订阅者回复后,再转发下一个订阅者。 +- 有序公共事件:CES转发公共事件时,根据订阅者设置的优先级等级,在接收到优先级较高的一个订阅者回复后,再向下一个优先级较低的订阅者转发公共事件。具有相同优先级的订阅者将按随机顺序收到公共事件。 -- 粘性公共事件:能够让订阅者收到在订阅前已经发送的公共事件就是粘性公共事件。普通的公共事件只能在订阅后发送才能收到,而粘性公共事件的特殊性就是可以先发送后订阅。发送粘性事件必须是系统应用或系统服务,且需要申请`ohos.permission.COMMONEVENT_STICKY`权限,配置方式请参见[访问控制授权申请](../security/accesstoken-guidelines.md#配置文件权限声明)。 +- 粘性公共事件:能够让订阅者收到在订阅前已经发送的公共事件就是粘性公共事件。普通的公共事件只能在订阅后发送才能收到,而粘性公共事件的特殊性就是可以先发送后订阅,同时也支持先订阅后发送。发送粘性事件必须是系统应用或系统服务,粘性事件发送后会一直存在系统中,且发送者需要申请`ohos.permission.COMMONEVENT_STICKY`权限,配置方式请参见[访问控制授权申请](../security/accesstoken-guidelines.md#配置文件权限声明)。 每个应用都可以按需订阅公共事件,订阅成功,当公共事件发布时,系统会将其发送给对应的应用。这些公共事件可能来自系统、其他应用和应用自身。 diff --git a/zh-cn/application-dev/application-models/common-event-static-subscription.md b/zh-cn/application-dev/application-models/common-event-static-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..c8c8c484a42012d2de4bd8a369226a9c8f01d867 --- /dev/null +++ b/zh-cn/application-dev/application-models/common-event-static-subscription.md @@ -0,0 +1,110 @@ +# 静态订阅公共事件(仅对系统应用开放) + +## 场景介绍 + +静态订阅者在未接收订阅的目标事件时,处于未拉起状态,当系统或应用发布了指定的公共事件后,静态订阅者将被拉起,并执行onReceiveEvent回调,开发者可通过在onReceiveEvent回调中执行业务逻辑,实现当应用接收到特定公共事件时执行业务逻辑的目的。例如,某应用希望在设备开机的时候执行一些初始化任务,那么该应用可以静态订阅开机事件,在收到开机事件后会拉起该应用,然后执行初始化任务。静态订阅是通过配置文件声明和实现继承自StaticSubscriberExtensionAbility的类实现对公共事件的订阅。**需要注意的是,静态订阅公共事件对系统功耗有一定影响,建议谨慎使用**。 + + + +## 开发步骤 + +1. 静态订阅者声明 + + 声明一个静态订阅者,首先需要在工程中新建一个ExtensionAbility, 该ExtensionAbility从StaticSubscriberExtensionAbility派生,其代码实现如下: + + ```ts + import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' + + export default class StaticSubscriber extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event:' + event.event); + } + } + ``` + + 开发者可以在onReceiveEvent中实现业务逻辑。 + + + +2. 静态订阅者工程配置 + + 在完成静态订阅者的代码实现后,需要将该订阅者配置到系统的module.json5中,配置形式如下: + + ```ts + { + "module": { + ...... + "extensionAbilities": [ + { + "name": "StaticSubscriber", + "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", + "description": "$string:StaticSubscriber_desc", + "icon": "$media:icon", + "label": "$string:StaticSubscriber_label", + "type": "staticSubscriber", + "visible": true, + "metadata": [ + { + "name": "ohos.extension.staticSubscriber", + "resource": "$profile:subscribe" + } + ] + } + ] + ...... + } + } + ``` + + 上述json文件主要关注以下字段: + + - srcEntrance : 表示ExtensionAbility的入口文件路径,即步骤2中声明的静态订阅者所在的文件路径 + + - type: 表示ExtensionAbility的类型,对于静态订阅者需要声明为“staticSubscriber” + + - metadata: 表示ExtensionAbility的二级配置文件信息。由于不同的ExtensionAbility类型其配置信息不尽相同,因此需要使用不同的config文件表示其具体配置信息。 + - name:表示ExtensionAbility的类型名称,对于静态订阅类型,name必须声明为“ohos.extension.staticSubscriber”,否则无法识别为静态订阅者; + - resource: 字段表示ExtensionAbility的配置信息路径,由开发者自行定义,在本例中表示路径为“resources/base/profile/subscribe.json"。 + + metadata指向的二级配置文件的通常形式如下: + + ```ts + { + "commonEvents": [ + { + "name": "xxx", + "permission": "xxx", + "events":[ + "xxx" + ] + } + ] + } + ``` + + 需要注意二级配置文件必须按照此形式进行声明,否则会无法正确识别。下面对字段进行介绍: + + - name: 静态订阅ExtensionAbility的名称,需要和module.json5中声明的ExtensionAbility的name一致 + + - permission:订阅者要求的发布者需要具备的权限,对于发布了目标事件但不具备permission中声明的权限的发布者将被视为非法事件不予发布 + + - events: 订阅的目标事件列表 + +3. 修改设备系统配置文件 + + 修改设备系统配置文件 **/system/etc/app/install_list_capability.json**,将静态订阅应用者的包名添加至该json文件中即可。 + + ```json + { + "install_list": [ + { + "bundleName": "ohos.extension.staticSubscriber", + "allowCommonEvent": ["usual.event.A", "usual.event.B"], + } + ] + } + ``` +## 相关示例 + +针对StaticSubscriberExtensionAbility开发,可参考如下实例:[StaticSubscriber:静态订阅(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber) + diff --git a/zh-cn/application-dev/application-models/common-event-subscription-overview.md b/zh-cn/application-dev/application-models/common-event-subscription-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..83a4518283b9173dcbab7b7c8694eff9a2dd9704 --- /dev/null +++ b/zh-cn/application-dev/application-models/common-event-subscription-overview.md @@ -0,0 +1,7 @@ +# 公共事件订阅概述 + +​公共事件服务提供了动态订阅和静态订阅两种订阅方式。动态订阅与静态订阅最大的区别在于,动态订阅是应用运行时行为,而静态订阅是后台服务无需处于运行状态。 + +- 动态订阅:指订阅方在运行时调用公共事件订阅的API实现对公共事件的订阅,详见[动态订阅公共事件](common-event-subscription.md)。 + +- 静态订阅:订阅方通过配置文件声明和实现继承自StaticSubscriberExtensionAbility的类实现对公共事件的订阅,详见[静态订阅公共事件](common-event-static-subscription.md)。 \ No newline at end of file diff --git a/zh-cn/application-dev/application-models/common-event-subscription.md b/zh-cn/application-dev/application-models/common-event-subscription.md index 785ea8d3a19fbeee57d938a07955370f0f3ca2b3..151c31927e1a0ed27a0520c993e83ecaa9a0389b 100644 --- a/zh-cn/application-dev/application-models/common-event-subscription.md +++ b/zh-cn/application-dev/application-models/common-event-subscription.md @@ -1,9 +1,9 @@ -# 公共事件订阅 +# 动态订阅公共事件 ## 场景介绍 -当需要订阅某个公共事件,获取该公共事件传递的参数时,需要创建一个订阅者对象,用于作为订阅公共事件的载体,订阅公共事件并获取公共事件传递而来的参数。订阅部分系统公共事件需要先[申请权限](../security/accesstoken-guidelines.md),订阅这些事件所需要的权限请见[公共事件权限列表](../reference/apis/js-apis-commonEventManager.md#support)。 +动态订阅是指当应用在运行状态时对某个公共事件进行订阅,在运行期间如果有订阅的事件发布那么订阅了这个事件的应用将会收到该事件及其传递的参数。例如,某应用希望在其运行期间收到电量过低的事件,并根据该事件降低其运行功耗,那么该应用便可动态订阅电量过低事件,收到该事件后关闭一些非必要的任务来降低功耗。订阅部分系统公共事件需要先[申请权限](../security/accesstoken-guidelines.md),订阅这些事件所需要的权限请见[公共事件权限列表](../reference/apis/js-apis-commonEventManager.md#support)。 ## 接口说明 diff --git a/zh-cn/application-dev/application-models/common-event-unsubscription.md b/zh-cn/application-dev/application-models/common-event-unsubscription.md index 1f7a23db104b8a8725b5d7711bd5a0dcb223b55f..fea148863efaf2155981c17600eacc8524b8e313 100644 --- a/zh-cn/application-dev/application-models/common-event-unsubscription.md +++ b/zh-cn/application-dev/application-models/common-event-unsubscription.md @@ -1,9 +1,9 @@ -# 公共事件取消订阅 +# 取消动态订阅公共事件 ## 场景介绍 -订阅者完成业务需要时,需要主动取消订阅,订阅者通过调用[unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe)方法取消订阅事件。 +动态订阅者完成业务需要时,需要主动取消订阅,订阅者通过调用[unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe)方法取消订阅事件。 ## 接口说明 @@ -21,7 +21,7 @@ import commonEventManager from '@ohos.commonEventManager'; ``` -2. 根据[公共事件订阅](common-event-subscription.md)章节的步骤来订阅某个事件。 +2. 根据[动态订阅公共事件](common-event-subscription.md)章节的步骤来订阅某个事件。 3. 调用CommonEvent中的unsubscribe()方法取消订阅某事件。 diff --git a/zh-cn/application-dev/application-models/enterprise-extensionAbility.md b/zh-cn/application-dev/application-models/enterprise-extensionAbility.md index b418036d0faacb55d22a3ae4ed96d5db25a60c1a..158b3eb4801466805d8261919edc479a96f3b7b1 100644 --- a/zh-cn/application-dev/application-models/enterprise-extensionAbility.md +++ b/zh-cn/application-dev/application-models/enterprise-extensionAbility.md @@ -2,18 +2,16 @@ ## EnterpriseAdminExtensionAbility简介 -企业设备管理扩展能力,是MDM应用必备组件。当开发者为企业开发MDM(Mobilie Device Management)应用时,需继承EnterpriseAdminExtensionAbility,在EnterpriseAdminExtensionAbility实例中实现MDM业务逻辑,EnterpriseAdminExtensionAbility实现了系统管理状态变化通知功能,并定义了管理应用激活、去激活、应用安装、卸载事件等回调接口。 +企业设备管理扩展能力,是MDM(Mobile Device Management)应用必备组件。当开发者为企业开发MDM应用时,需继承EnterpriseAdminExtensionAbility,在EnterpriseAdminExtensionAbility实例中实现MDM业务逻辑,EnterpriseAdminExtensionAbility实现了系统管理状态变化通知功能,并定义了管理应用激活、去激活、应用安装、卸载事件等回调接口。 ## 约束与限制 -- **_功能限制_** - - 仅支持设备管理员应用使用。 + 仅支持设备管理员应用使用。(功能限制) -## 场景:监听设备管理器激活、去激活、应用安装、卸载事件 +## 场景:监听设备管理器激活、去激活、应用安装、卸载事件 -## 概述 +### 概述 onAdminEnabled:由企业管理员或者员工部署MDM应用,激活设备管理器,系统通知MDM应用已激活DeviceAdmin权限。MDM应用可在onAdminEnabled回调函数中进行初始化策略设置。 @@ -23,7 +21,7 @@ onBundleAdded: 企业应用管理场景下,企业管理员订阅应用安装 onBundleRemoved: 企业应用管理场景下,企业管理员取消订阅应用安装卸载事件。 -## 接口说明 +### 接口说明 | 类名 | 接口名称 | 描述 | | :------------------------------ | ----------------------------------------- | ---------------------------- | @@ -32,13 +30,13 @@ onBundleRemoved: 企业应用管理场景下,企业管理员取消订阅应用 | EnterpriseAdminExtensionAbility | onAdminEnabled(): void | 设备管理器应用激活回调方法 | | EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | 应用卸载回调方法 | -## 开发步骤 +### 开发步骤 -开发者在实现EnterpriseAdminExtensionAbility的时候,需先激活设备管理员应用,并在设备管理员应用的代码目录下载新建ExtensionAbility,具体步骤如下。 +开发者在实现EnterpriseAdminExtensionAbility的时候,需先激活设备管理员应用,并在设备管理员应用的代码目录下新建ExtensionAbility,具体步骤如下。 1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为EnterpriseExtAbility。 2. 在EnterpriseExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为EnterpriseExtAbility.ts。 -3. 打开EnterpriseExtAbility.ts文件,导入EnterpriseAdminExtensionAbility模块,自定义类继承EnterpriseAdminExtensionAbility并加上需要的应用通知回调方法,如onAdminEnabled()、onAdminDisabled()等回调方法。当设备管理员应用被激活或则去激活时,则可以在对应回调方法中接受系统发送通知。 +3. 打开EnterpriseExtAbility.ts文件,导入EnterpriseAdminExtensionAbility模块,自定义类继承EnterpriseAdminExtensionAbility并加上需要的应用通知回调方法,如onAdminEnabled()、onAdminDisabled()等回调方法。当设备管理员应用被激活或者去激活时,则可以在对应回调方法中接受系统发送通知。 ```ts import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility'; diff --git a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md index 411f454354fd2c430eff1badf41b759485d9aab0..4e8851aca08ad2ed5906db94af9fc24f25f281d6 100644 --- a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md +++ b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md @@ -319,8 +319,8 @@ | startAbilityByCall(want: Want): Promise<Caller>; | 启动指定UIAbility至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。 | | on(method: string, callback: CalleeCallBack): void | 通用组件Callee注册method对应的callback方法。 | | off(method: string): void | 通用组件Callee解注册method的callback方法。 | -| call(method: string, data: rpc.Sequenceable): Promise<void> | 向通用组件Callee发送约定序列化数据。 | -| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | 向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。 | +| call(method: string, data: rpc.Parcelable): Promise<void> | 向通用组件Callee发送约定序列化数据。 | +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | 向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。 | | release(): void | 释放通用组件的Caller通信接口。 | | on(type: "release", callback: OnReleaseCallback): void | 注册通用组件通信断开监听通知。 | @@ -377,7 +377,7 @@ ```ts - export default class MySequenceable { + export default class MyParcelable { num: number = 0; str: string = ""; @@ -386,15 +386,15 @@ this.str = string; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } @@ -410,13 +410,13 @@ console.info('CalleeSortFunc called'); // 获取Caller发送的序列化数据 - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); // 作相应处理 // 返回序列化数据result给Caller - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); + return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); } export default class CalleeAbility extends Ability { @@ -476,13 +476,13 @@ getRemoteDeviceId方法参照[通过跨设备启动uiability和serviceextensionability组件实现多端协同无返回数据](#通过跨设备启动uiability和serviceextensionability组件实现多端协同无返回数据)。 5. 向被调用端UIAbility发送约定序列化数据。 - 1. 向被调用端发送Sequenceable数据有两种方式,一种是不带返回值,一种是获取被调用端返回的数据,method以及序列化数据需要与被调用端协商一致。如下示例调用Call接口,向Callee被调用端发送数据。 + 1. 向被调用端发送Parcelable数据有两种方式,一种是不带返回值,一种是获取被调用端返回的数据,method以及序列化数据需要与被调用端协商一致。如下示例调用Call接口,向Callee被调用端发送数据。 ```ts const MSG_SEND_METHOD: string = 'CallSendMsg'; async onButtonCall() { try { - let msg = new MySequenceable(1, 'origin_Msg'); + let msg = new MyParcelable(1, 'origin_Msg'); await this.caller.call(MSG_SEND_METHOD, msg); } catch (error) { console.info(`caller call failed with ${error}`); @@ -497,12 +497,12 @@ backMsg: string = ''; async onButtonCallWithResult(originMsg, backMsg) { try { - let msg = new MySequenceable(1, originMsg); + let msg = new MyParcelable(1, originMsg); const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg); console.info('caller callWithResult succeed'); - let result = new MySequenceable(0, ''); - data.readSequenceable(result); + let result = new MyParcelable(0, ''); + data.readParcelable(result); backMsg(result.str); console.info(`caller result is [${result.num}, ${result.str}]`); } catch (error) { diff --git a/zh-cn/application-dev/application-models/itc-with-worker.md b/zh-cn/application-dev/application-models/itc-with-worker.md index 98f467cf74b2f3d3596d03a3b8074b4f7c6cfad2..994e3734307372051c32a2bae272bcb8b2977424 100644 --- a/zh-cn/application-dev/application-models/itc-with-worker.md +++ b/zh-cn/application-dev/application-models/itc-with-worker.md @@ -19,7 +19,7 @@ Worker的开发步骤如下: } ``` -2. 根据build-profile.json5中的配置创建对应的worker.js文件。 +2. 根据build-profile.json5中的配置创建对应的worker.ts文件。 ```ts import worker from '@ohos.worker'; @@ -59,7 +59,7 @@ Worker的开发步骤如下: ```ts import worker from '@ohos.worker'; - let wk = new worker.ThreadWorker("../workers/worker.js"); + let wk = new worker.ThreadWorker("../workers/worker.ts"); // 发送消息到worker线程 wk.postMessage("message from main thread.") @@ -75,6 +75,6 @@ Worker的开发步骤如下: **说明:** -- build-profile.json5中配置的worker.ts的相对路径都为`./src/main/ets/workers/worker.ts`时,在Stage模型下创建worker需要传入路径`entry/ets/workers/worker.ts`;在FA模型下创建worker需要传入路径`../workers/worker.js`。 +- build-profile.json5中配置的worker.ts的相对路径都为`./src/main/ets/workers/worker.ts`时,在Stage模型下创建worker需要传入路径`entry/ets/workers/worker.ts`;在FA模型下创建worker需要传入路径`../workers/worker.ts`。 -- 主线程与Worker线程间支持的数据类型参考[序列化支持类型](../reference/apis/js-apis-worker.md#%E5%BA%8F%E5%88%97%E5%8C%96%E6%94%AF%E6%8C%81%E7%B1%BB%E5%9E%8B)。 +- 主线程与Worker线程间支持的数据类型参考[序列化支持类型](../reference/apis/js-apis-worker.md#序列化支持类型)。 diff --git a/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md b/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md deleted file mode 100644 index c3710ea14ed77077049e4a7c5289160b5498063d..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md +++ /dev/null @@ -1,108 +0,0 @@ -# StaticSubscriberExtensionAbility开发指导 - -## 场景介绍 - -​公共事件服务提供了动态订阅和静态订阅两种订阅方式。动态订阅即订阅方在运行期调用公共事件订阅的API实现对公共事件的订阅,详见[公共事件订阅](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/application-models/common-event-subscription.md)。与动态订阅相对应的是静态订阅方式,这种方式不需要主动调用公共事件的API,而是通过配置文件声明和实现继承自StaticSubscriberExtensionAbility的类实现对公共事件的订阅。静态订阅者在未接收订阅的目标事件时,处于未拉起状态,当系统或应用发布了指定的公共事件后,静态订阅者将被拉起,并执行onReceiveEvent回调,开发者可通过在onReceiveEvent回调中执行业务逻辑,实现当应用接收到特定公共事件(例如开机事件)时执行业务逻辑的目的。**需要注意的是,静态订阅能力严格受限,相关接口为系统API,仅限于经过系统层面功耗评审的特定系统应用使用**。 - - - -## 开发步骤 - -1. 前置条件 - - 请确保您的应用具备以下特征: - - 1)系统应用 - - 2)使用full-sdk开发 - - 3)经过性能功耗团队评审符合功耗要求,如果您希望在调试阶段尝试使用该功能,可修改系统配置文件/etc/static_subscriber_config.json,将待调试应用的包名添加至json文件中即可。 - - - -2. 静态订阅者声明 - - 声明一个静态订阅者,首先需要在工程中新建一个ExtensionAbility, 该ExtensionAbility从StaticSubscriberExtensionAbility派生,其代码实现如下: - - ```ts - import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' - - export default class StaticSubscriber extends StaticSubscriberExtensionAbility { - onReceiveEvent(event) { - console.log('onReceiveEvent, event:' + event.event); - } - } - ``` - - 开发者可以在onReceiveEvent中实现业务逻辑。 - - - -3. 静态订阅者工程配置 - - 在完成静态订阅者的代码实现后,需要将该订阅者配置到系统的module.json5中,配置形式如下: - - ```ts - { - "module": { - ...... - "extensionAbilities": [ - { - "name": "StaticSubscriber", - "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", - "description": "$string:StaticSubscriber_desc", - "icon": "$media:icon", - "label": "$string:StaticSubscriber_label", - "type": "staticSubscriber", - "visible": true, - "metadata": [ - { - "name": "ohos.extension.staticSubscriber", - "resource": "$profile:subscribe" - } - ] - } - ] - ...... - } - } - ``` - - 上述json文件主要关注以下字段: - - **srcEntrance**: 表示extension的入口文件路径,即步骤2中声明的静态订阅者所在的文件路径 - - **type**: 表示extension的类型,对于静态订阅者需要声明为“staticSubscriber” - - **metadata**: 表示extension的二级配置文件信息。由于不同的extension类型其配置信息不尽相同,因此需要使用不同的config文件表示其具体配置信息。metadata字段共包含两个关键字name和resource。其中name字段表示extension的类型名称,对于静态订阅类型,name必须声明为“ohos.extension.staticSubscriber”,否则无法识别为静态订阅者;resource字段表示extension的配置信息路径,由开发者自行定义,在本例中表示路径为“resources/base/profile/subscribe.json"。 - - metadata指向的二级配置文件的通常形式如下: - - ```ts - { - "commonEvents": [ - { - "name": "xxx", - "permission": "xxx", - "events":[ - "xxx" - ] - } - ] - } - ``` - - 需要注意二级配置文件必须按照此形式进行声明,否则会无法正确识别。下面对字段进行介绍: - - **name**: 静态订阅extension的名称,需要和module.json5中声明的extensionAbility的name一致 - - **permission**:订阅者要求的发布者需要具备的权限,对于发布了目标事件但不具备permission中声明的权限的发布者将被视为非法事件不予发布 - - **events**: 订阅的目标事件列表 - - - -## 相关示例 - -针对StaticSubscriberExtensionAbility开发,可参考如下实例:[StaticSubscriber:静态订阅(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber) - diff --git a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md index f15f50ac5b9b33a6b3d554db4ff5112944e486fe..298ec3f6bf415a2a5e036969df20452877a8c5b4 100644 --- a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md +++ b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md @@ -525,8 +525,8 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe | startAbilityByCall(want: Want): Promise<Caller> | 启动指定UIAbility并获取其Caller通信接口,默认为后台启动,通过配置want可实现前台启动,详见[接口文档](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall)。AbilityContext与ServiceExtensionContext均支持该接口。 | | on(method: string, callback: CalleeCallBack): void | 通用组件Callee注册method对应的callback方法。 | | off(method: string): void | 通用组件Callee解注册method的callback方法。 | -| call(method: string, data: rpc.Sequenceable): Promise<void> | 向通用组件Callee发送约定序列化数据。 | -| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | 向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。 | +| call(method: string, data: rpc.Parcelable): Promise<void> | 向通用组件Callee发送约定序列化数据。 | +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | 向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。 | | release(): void | 释放通用组件的Caller通信接口。 | | on(type: "release", callback: OnReleaseCallback): void | 注册通用组件通信断开监听通知。 | @@ -574,7 +574,7 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe ```ts - export default class MySequenceable { + export default class MyParcelable { num: number = 0 str: string = "" @@ -583,15 +583,15 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe this.str = string } - marshalling(messageParcel) { - messageParcel.writeInt(this.num) - messageParcel.writeString(this.str) + marshalling(messageSequence) { + messageSequence.writeInt(this.num) + messageSequence.writeString(this.str) return true } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt() - this.str = messageParcel.readString() + unmarshalling(messageSequence) { + this.num = messageSequence.readInt() + this.str = messageSequence.readString() return true } } @@ -609,13 +609,13 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe console.info('CalleeSortFunc called'); // 获取Caller发送的序列化数据 - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); // 作相应处理 // 返回序列化数据result给Caller - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); + return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); } export default class CalleeAbility extends Ability { diff --git a/zh-cn/application-dev/connectivity/http-request.md b/zh-cn/application-dev/connectivity/http-request.md index ff6ec5ed4113c8c9c14cb6a1613dd86dab7ff232..8c4c663fcc800a1998168aed065fd3e568a5e329 100644 --- a/zh-cn/application-dev/connectivity/http-request.md +++ b/zh-cn/application-dev/connectivity/http-request.md @@ -30,7 +30,7 @@ HTTP数据请求功能主要由http模块提供。 | on\('dataProgress'\)10+ | 订阅HTTP流式响应数据接收进度事件。 | | off\('dataProgress'\)10+ | 取消订阅HTTP流式响应数据接收进度事件。 | -## 开发步骤 +## request接口开发步骤 1. 从@ohos.net.http.d.ts中导入http命名空间。 2. 调用createHttp()方法,创建一个HttpRequest对象。 @@ -83,7 +83,7 @@ httpRequest.request( console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 httpRequest.off('headersReceive'); - // 当该请求使用完毕时,调用destroy方法主动销毁。 + // 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy(); } } diff --git a/zh-cn/application-dev/connectivity/net-sharing.md b/zh-cn/application-dev/connectivity/net-sharing.md index 337939b95247169c84a6bbae1e3fb313b27afd82..62b8ea0e8ea6470facad70b1a9edd4b1fe0dac91 100644 --- a/zh-cn/application-dev/connectivity/net-sharing.md +++ b/zh-cn/application-dev/connectivity/net-sharing.md @@ -63,7 +63,7 @@ }); // 调用startSharing方法,来开启指定类型共享 - sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -88,7 +88,7 @@ }); // 调用stopSharing方法,来停止指定类型共享 - sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -107,7 +107,7 @@ import sharing from '@ohos.net.sharing' // 调用startSharing方法,来开启指定类型共享 - sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); @@ -118,7 +118,7 @@ }); // 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 - sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); diff --git a/zh-cn/application-dev/connectivity/socket-connection.md b/zh-cn/application-dev/connectivity/socket-connection.md index ab896fdfe7ac0b9c5669b2df7e12614b30867c9d..1d9cf0a6c51205c342687aec7a1b927852a42658 100644 --- a/zh-cn/application-dev/connectivity/socket-connection.md +++ b/zh-cn/application-dev/connectivity/socket-connection.md @@ -49,6 +49,7 @@ TLS Socket连接主要由tls_socket模块提供。具体接口说明如下表。 | 接口名 | 功能描述 | | -------- | -------- | +| constructTLSSocketInstance() | 创建一个TLSSocket对象。 | | bind() | 绑定IP地址和端口号。 | | close(type: 'error') | 关闭连接。 | | connect() | 连接到指定的IP地址和端口。 | @@ -189,7 +190,7 @@ UDP与TCP流程大体类似,下面以TCP为例: let tlsTwoWay = socket.constructTLSSocketInstance(); // 订阅TLS Socket相关的订阅事件 - tcp.on('message', value => { + tlsTwoWay.on('message', value => { console.log("on message") let buffer = value.message let dataView = new DataView(buffer) @@ -199,10 +200,10 @@ UDP与TCP流程大体类似,下面以TCP为例: } console.log("on connect received:" + str) }); - tcp.on('connect', () => { + tlsTwoWay.on('connect', () => { console.log("on connect") }); - tcp.on('close', () => { + tlsTwoWay.on('close', () => { console.log("on close") }); @@ -246,22 +247,22 @@ UDP与TCP流程大体类似,下面以TCP为例: }); // 连接使用完毕后,主动关闭。取消相关事件的订阅。 - tls.close((err) => { + tlsTwoWay.close((err) => { if (err) { console.log("close callback error = " + err); } else { console.log("close success"); } - tls.off('message'); - tls.off('connect'); - tls.off('close'); + tlsTwoWay.off('message'); + tlsTwoWay.off('connect'); + tlsTwoWay.off('close'); }); // 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication // 订阅TLS Socket相关的订阅事件 - tcp.on('message', value => { + tlsTwoWay.on('message', value => { console.log("on message") let buffer = value.message let dataView = new DataView(buffer) @@ -271,10 +272,10 @@ UDP与TCP流程大体类似,下面以TCP为例: } console.log("on connect received:" + str) }); - tcp.on('connect', () => { + tlsTwoWay.on('connect', () => { console.log("on connect") }); - tcp.on('close', () => { + tlsTwoWay.on('close', () => { console.log("on close") }); @@ -307,15 +308,15 @@ UDP与TCP流程大体类似,下面以TCP为例: }); // 连接使用完毕后,主动关闭。取消相关事件的订阅。 - tls.close((err) => { + tlsTwoWay.close((err) => { if (err) { console.log("close callback error = " + err); } else { console.log("close success"); } - tls.off('message'); - tls.off('connect'); - tls.off('close'); + tlsTwoWay.off('message'); + tlsTwoWay.off('connect'); + tlsTwoWay.off('close'); }); ``` diff --git a/zh-cn/application-dev/dfx/apprecovery-guidelines.md b/zh-cn/application-dev/dfx/apprecovery-guidelines.md index c2293d0eced73f280e532fca427d7e812eb62209..393083bb068e7f282675e166e24c012e2dd0e877 100644 --- a/zh-cn/application-dev/dfx/apprecovery-guidelines.md +++ b/zh-cn/application-dev/dfx/apprecovery-guidelines.md @@ -5,35 +5,54 @@ 应用在运行中不可避免会产生一些非预期的行为,如运行时抛出未处理的异常和错误,违反框架的调用/运行约束等。 系统默认对异常的处理方式为进程退出,如果应用使用过程中产生了用户数据,直接退出可能会导致用户工作中断,数据丢失。 -如果使用应用故障恢复相关接口,则可对临时数据进行保存,应用退出后会重启应用并恢复先前的状态和数据,能给用户带来更好的使用体验。 +如果应用使能了应用恢复功能,并对临时数据进行保存,应用非预期退出后的下一次启动会恢复先前的状态和数据,给用户更连贯的使用体验。这里状态包括应用的页面栈以及onSaveState接口中保存的数据。 -目前该接口仅支持单进程单Ability的Stage模型应用开发。 +API 9上的应用恢复接口支持单Ability的Stage模型应用开发。支持JsError故障时的状态保存与自动重启。 + +API 10在API 9的基础上新增支持多Ability的Stage模型应用开发。支持AppFreeze故障时的状态保存回调。支持应用被管控模式杀死后,下次启动的状态恢复。 ## 接口说明 -应用故障恢复接口由appRecovery模块提供,开发者可以通过import引入,详见[开发示例](#开发示例)。本文档描述的为API9版本的接口行为,后续接口行为变更会更新本文档。 +应用故障恢复接口由appRecovery模块提供,开发者可以通过import引入,详见[开发示例](#开发示例)。 ### 应用恢复接口功能介绍 | 接口名称 | 说明 | | ------------------------------------------------------------ | ---------------------------------------------------- | -| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | 使能应用恢复功能。| -| saveAppState(): boolean; | 主动保存当前应用中Ability的状态。 | -| restartApp(): void; | 重启当前进程,如果有已经保存的Ability状态,会在Ability的OnCreate生命周期回调的want参数中的wantParam属性传入。 | +| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void;9+ | 使能应用恢复功能,参数按顺序填入。该接口调用后,应用从启动器启动时第一个Ability支持恢复。| +| saveAppState(): boolean;9+ | 主动保存当前应用中支持恢复的Ability的状态。 | +| restartApp(): void;9+ | 重启当前进程,并启动由**setRestartWant**指定的Ability,如果未指定,将重新拉起处于前台且支持恢复的Ability。 | +| saveAppState(context?: UIAbilityContext): boolean;10+ | 主动保存由Context指定的Ability状态。 | +| setRestartWant(want: Want): void;10+ | 设置主动调用**restartApp**以及**RestartFlag**不为**NO_RESTART**时重启的Ability。该Ability必须在同一个包名下,且必须为**UiAbility**。 | -由于本接口为故障处理时使用,不会返回异常,需要开发者熟悉使用的场景。 +由于上述接口可能在故障处理时使用,所以不会返回异常,需要开发者熟悉使用的场景。 **enableAppRecovery:** 需要在应用初始化阶段调用,比如AbilityStage的OnCreate调用赋能。具体其各参数定义详见[参数说明](../reference/apis/js-apis-app-ability-appRecovery.md)。 -**saveAppState:** 调用后框架会回调Ability的onSaveState方法,如果在onSaveState方法中同意保存数据,则会将相关数据及Ability的页面栈持久化到应用的本地缓存。 +**saveAppState:** 调用后框架会回调**当前进程中所有支持恢复的Ability**的onSaveState方法,如果在onSaveState方法中同意保存数据,则会将相关数据及Ability的页面栈持久化到应用的本地缓存。如果需要保存指定Ability,则需要指定Ability对应的Context。 + +**setRestartWant:** 指定由appRecovery发起重启的Ability。 + +**restartApp:** 调用后框架会杀死当前应用进程,并重新拉起由**setRestartWant**指定的Ability,其中启动原因为APP_RECOVERY。API 9以及未使用**setRestartWant**指定Ability的场景,会拉起最后一个支持恢复且在前台的Ability,如果当前前台的Ability不支持恢复,则应用表现闪退。如果重启的Ability存在已经保存的状态,这些状态数据会在Ability的OnCreate生命周期回调的want参数中作为wantParam属性传入。 + +### 应用恢复状态管理示意 +从API 10起,应用恢复的场景不仅局限于异常时自动重启。所以需要理解应用何时会加载恢复的状态。 +一句话概括就是**如果应用任务的上次退出不是由用户发起的,且应用存在用于恢复的状态,应用下一次由用户拉起时的启动原因会被设为APP_RECOVERY,并清理该任务的恢复状态。** +应用恢复状态标识会在状态保存接口主动或者被动调用时设置。在该任务正常退出或者消费了该状态时清理。正常退出目前包括用户按**后退键退出**以及用户**清理最近任务**。 + +![应用恢复状态管理示意](./figures/20230315112155.png) -**restartApp:** 调用后框架会杀死当前应用进程,并重新拉起处于前台的Ability,其中启动原因为APP_RECOVERY。 +### 应用卡死的状态保存及恢复 +API 10开始支持应用卡死时的状态保存。JsError故障时,onSaveState接口在主线程进行回调。对于AppFreeze故障,主线程可能处于卡死的状态,onSaveState会在非主线程进行回调。其主要流程如下图: + +![应用卡死状态保存恢复示意](./figures/20230315112235.png) +由于卡死时的回调不在JS线程上执行,onSaveState回调中的代码建议不要使用import进来的Native动态库,禁止访问主线程创建的thread_local对象。 ### 框架故障管理流程示意 故障管理是应用提升用户体验的重要手段。应用程序框架为开发者提供了故障监听、故障恢复、以及故障查询三种方式来管理应用的故障。 -- 故障监听指的是通过[errorManager](../reference/apis/js-apis-application-errorManager.md)注册[ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver),监听故障的发生,并通知到监听方。 +- 故障监听指的是通过[errorManager](../reference/apis/js-apis-app-ability-errorManager.md)注册[ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md),监听故障的发生,并通知到监听方。 - 故障恢复指的是[appRecovery](../reference/apis/js-apis-app-ability-appRecovery.md),及故障发生后,将应用重启恢复到故障之前的状态。 @@ -41,9 +60,9 @@ 下图中并没有标记[faultLogger](../reference/apis/js-apis-faultLogger.md)的调用时机,开发者可以根据应用启动时传入的[LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason)来决定是否调用[faultLogger](../reference/apis/js-apis-faultLogger.md)查询上次的故障信息。 ![故障处理流程示意](./figures/20221106203527.png) -这里建议应用开发者使用[errorManager](../reference/apis/js-apis-application-errorManager.md)对应用的异常进行处理,处理完成后开发者可以选择调用状态保存接口并主动重启应用。 -如果开发者没有注册[ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver)也没有使能自动恢复,则按照系统的默认逻辑执行进程退出。用户可以选择从启动器再次打开应用。 -如果开发者使能了自动恢复,框架会首先检查当前故障是否支持状态保存以及开发者是否配置了状态保存,如果支持则会回调[Ability](../reference/apis/js-apis-application-ability.md#ability)的[onSaveState](../reference/apis/js-apis-application-ability.md#abilityonsavestate)的接口。最后重启应用。 +这里建议应用开发者使用[errorManager](../reference/apis/js-apis-app-ability-errorManager.md)对应用的异常进行处理,处理完成后开发者可以选择调用状态保存接口并主动重启应用。 +如果开发者没有注册[ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md)也没有使能自动恢复,则按照系统的默认逻辑执行进程退出。用户可以选择从启动器再次打开应用。 +如果开发者使能了自动恢复,框架会首先检查当前故障是否支持状态保存以及开发者是否配置了状态保存,如果支持则会回调[Ability](../reference/apis/js-apis-app-ability-uiAbility.md)的[onSaveState](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonsavestate)的接口。最后重启应用。 ### 应用故障管理接口支持场景 @@ -52,7 +71,7 @@ | 故障名称 | 故障监听 | 状态保存 | 自动重启 | 日志查询 | | ----------|--------- |--------- |--------- |--------- | | [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | 支持|支持|支持|支持| -| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | 不支持|不支持|支持|支持| +| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | 不支持|支持|支持|支持| | [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | 不支持|不支持|不支持|支持| 这里状态保存指的是故障时状态保存,对于应用卡死场景,开发者可以采用定时保存状态或者在Ability切入后台后自动保存的方式最大限度的保护用户数据。 @@ -77,6 +96,18 @@ export default class MyAbilityStage extends AbilityStage { appRecovery.SaveModeFlag.SAVE_WITH_FILE); } } +``` +### 配置支持恢复的Ability +Ability的配置清单一般的名字为module.json5。 +```json +{ + "abilities": [ + { + "name": "EntryAbility", + "recoverable": true, + }] +} + ``` ### 数据保存和恢复 @@ -94,7 +125,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; #### 主动触发保存和恢复 -- 定义和注册[ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) callback +- 定义和注册[ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback ```ts var registerId = -1; diff --git a/zh-cn/application-dev/dfx/figures/20230315112155.png b/zh-cn/application-dev/dfx/figures/20230315112155.png new file mode 100644 index 0000000000000000000000000000000000000000..20324a0b23f2b409c2fef8daaa74bcccd5427398 Binary files /dev/null and b/zh-cn/application-dev/dfx/figures/20230315112155.png differ diff --git a/zh-cn/application-dev/dfx/figures/20230315112235.png b/zh-cn/application-dev/dfx/figures/20230315112235.png new file mode 100644 index 0000000000000000000000000000000000000000..34cf30ce75516810536335bd9a2789517360eae3 Binary files /dev/null and b/zh-cn/application-dev/dfx/figures/20230315112235.png differ diff --git a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md index 562ae00767b674be4423014cf1970b4759da5204..74a844f946099633f0389ea383d135a48dbfa328 100644 --- a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -135,7 +135,7 @@ async function copySandbox2Public() { console.error('file asset get failed, message = ' + err); } let fdPub = await fileAsset.open('rw'); - let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE); + let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE); await fs.copyFile(fdSand.fd, fdPub); await fileAsset.close(fdPub); await fs.close(fdSand.fd); diff --git a/zh-cn/application-dev/internationalization/intl-guidelines.md b/zh-cn/application-dev/internationalization/intl-guidelines.md index 8c4b8408bd12d3aa2b8a70309081ae8997d2e7b1..54440aa1a4acdf938b360fc0729a3c46de11019e 100644 --- a/zh-cn/application-dev/internationalization/intl-guidelines.md +++ b/zh-cn/application-dev/internationalization/intl-guidelines.md @@ -111,7 +111,7 @@ let dateTimeFormat = new Intl.DateTimeFormat(); ``` - 另一种方法是使用开发者提供的Locale和格式化参数来创建日期时间格式化对象。其中,格式化参数是可选的,完整的格式化参数列表见[DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions)。 + 另一种方法是使用开发者提供的Locale和格式化参数来创建日期时间格式化对象。其中,格式化参数是可选的,完整的格式化参数列表见[DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions9)。 ```js let options = {dateStyle: "full", timeStyle: "full"}; @@ -181,7 +181,7 @@ let numberFormat = new Intl.NumberFormat(); ``` - 另一种方法是使用开发者提供的Locale和格式化参数来创建数字格式化对象。其中,格式化参数是可选的,完整的格式化参数列表参见[NumberOptions](../reference/apis/js-apis-intl.md#numberoptions)。 + 另一种方法是使用开发者提供的Locale和格式化参数来创建数字格式化对象。其中,格式化参数是可选的,完整的格式化参数列表参见[NumberOptions](../reference/apis/js-apis-intl.md#numberoptions9)。 ```js let options = {compactDisplay: "short", notation: "compact"}; @@ -240,7 +240,7 @@ let collator = new Intl.Collator(); ``` - 另一种方法是使用开发者提供的Locale和其他相关参数来创建Collator对象,完整的参数列表参见[CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8)。 + 另一种方法是使用开发者提供的Locale和其他相关参数来创建Collator对象,完整的参数列表参见[CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9)。 其中,sensitivity参数用于控制哪些级别的差异会被用于比较两个字符串。取值"base"表示,仅比较字符本身,不考虑重音符号、大小写差异。例如,'a' != 'b','a' == 'á','a' == 'A'。取值"accent"表示考虑重音符号,不考虑大小写的差异。例如,'a' != 'b','a' != 'á','a' == 'A'。取值"case"表示考虑大小写的差异,不考虑重音符号的差异。例如,'a' != 'b','a' == 'á','a' != 'A'。取值"variant"表示考虑重音符号、大小写等方面差异。例如'a' != 'b','a' != 'á','a' != 'A'。 ```js @@ -301,7 +301,7 @@ let pluralRules = new Intl.PluralRules(); ``` - 另一种方法是使用开发者提供的Locale和其他相关参数来创建单复数对象。完整的参数列表参见[PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8)。 + 另一种方法是使用开发者提供的Locale和其他相关参数来创建单复数对象。完整的参数列表参见[PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9)。 ```js let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -349,7 +349,7 @@ let relativeTimeFormat = new Intl.RelativeTimeFormat(); ``` - 另一种方法是使用开发者提供的Locale和格式化参数来创建相对时间格式化对象。其中,格式化参数是可选的,完整的参数列表参见[ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8)。 + 另一种方法是使用开发者提供的Locale和格式化参数来创建相对时间格式化对象。其中,格式化参数是可选的,完整的参数列表参见[RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9)。 ```js let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md index 9bef5805ea054e71175ce023aba4247472f22c49..21d43d67cacb5fbaf07ea6c6f645dd416b65844f 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md @@ -11,12 +11,12 @@ 用户通过点击某个元素触发功能、访问新页面、或改变自身状态。 - | **输入方式** | **交互行为** | **示意** | +| **输入方式** | **交互行为** | **示意** | | -------- | -------- | -------- | -| 触屏 | 单指单击 | ![zh-cn_image_0000001280472681](figures/zh-cn_image_0000001280472681.png) | -| 鼠标 | 左键单击 / 左键双击 | ![zh-cn_image_0000001236472600](figures/zh-cn_image_0000001236472600.png) | -| 触摸板 | 单指单击 / 单指双击 | ![zh-cn_image_0000001280232265](figures/zh-cn_image_0000001280232265.png) | -| 键盘 | 移动焦点到对象上后按下Enter键 | ![zh-cn_image_0000001280472701](figures/zh-cn_image_0000001280472701.png) | +| 触屏 | 单指单击 | ![zh-cn_image_0000001280472681](figures/zh-cn_image_0000001280472681.png) | +| 鼠标 | 左键单击 / 左键双击 | ![zh-cn_image_0000001236472600](figures/zh-cn_image_0000001236472600.png) | +| 触摸板 | 单指单击 / 单指双击 | ![zh-cn_image_0000001280232265](figures/zh-cn_image_0000001280232265.png) | +| 键盘 | 移动焦点到对象上后按下Space键 | ![zh-cn_image_0000001280472701](figures/zh-cn_image_0000001280472701.png) | 一般地,触屏手指的按下/抬起行为对应于光标的按下/抬起行为。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png index cabcaf5667a4093f188b59b9ce092abd975ab5d8..a27b306ab5457819b1a57599e2a7a95d81faf5c3 100644 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md index cc900b99e416aec4dd418adb6f9385e6dcd35e44..270181beca5a233e31e91b90958b0a79174426f7 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md @@ -597,7 +597,7 @@ struct GridRowSample6 { **示例7:** -通过order属性,控制GridCol的顺序。在sm和md断点下,按照至6的顺序排列显示;在lg断点下,按照6至1的顺序排列显示。 +通过order属性,控制GridCol的顺序。在sm和md断点下,按照1至6的顺序排列显示;在lg断点下,按照6至1的顺序排列显示。 | sm | md | lg | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md index 4bb565e096bb61022c3f76f9256e0ed31054ed74..4262141b3c21f9c6deff4ed7776c3b01e1bbcb91 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md @@ -470,6 +470,7 @@ struct Item { NavDestination() { Details({imageSrc: this.imageSrc}) }.title(this.label) + .backgroundColor('#FFFFFF') } } } @@ -491,7 +492,7 @@ struct NavigationSample { .backgroundColor('#F1F3F5') .height('100%') .width('100%') - .navBarWidth('40%') + .navBarWidth(360) .hideToolBar(true) .title('Sample') } diff --git a/zh-cn/application-dev/media/audio-capturer.md b/zh-cn/application-dev/media/audio-capturer.md index 3d4ecec3a0bb0bbfa9ba8987f140e41659df4f59..451362be0bc16f24039f8aabea0c1bc7e12eb15f 100644 --- a/zh-cn/application-dev/media/audio-capturer.md +++ b/zh-cn/application-dev/media/audio-capturer.md @@ -27,32 +27,42 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md#audiocapturer8) -1. 使用createAudioCapturer()创建一个AudioCapturer实例。 +1. 使用createAudioCapturer()创建一个全局的AudioCapturer实例。 在audioCapturerOptions中设置音频采集器的相关参数。该实例可用于音频采集、控制和获取采集状态,以及注册通知回调。 ```js - import audio from '@ohos.multimedia.audio'; - - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - let audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 // 0是音频采集器的扩展标志位,默认为0 - } - - let audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - console.log('AudioRecLog: Create audio capturer success.'); + import audio from '@ohos.multimedia.audio'; + import fs from '@ohos.file.fs'; //便于步骤3 read函数调用 + + //音频渲染相关接口自测试 + @Entry + @Component + struct AudioRenderer { + @State message: string = 'Hello World' + private audioCapturer : audio.AudioCapturer; //供全局调用 + + async initAudioCapturer(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + let audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 // 0是音频采集器的扩展标志位,默认为0 + } + + let audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + this.audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + console.log('AudioRecLog: Create audio capturer success.'); + } ``` 2. 调用start()方法来启动/恢复采集任务。 @@ -60,23 +70,18 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 启动完成后,采集器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 ```js - import audio from '@ohos.multimedia.audio'; - - async function startCapturer() { - let state = audioCapturer.state; + async startCapturer() { + let state = this.audioCapturer.state; // Capturer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Capturer is not in a correct state to start'); - return; - } - await audioCapturer.start(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.error('AudioRecLog: Capturer start failed'); + if (state == audio.AudioState.STATE_PREPARED || state == audio.AudioState.STATE_PAUSED || + state == audio.AudioState.STATE_STOPPED) { + await this.audioCapturer.start(); + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.error('AudioRecLog: Capturer start failed'); + } } } ``` @@ -86,91 +91,88 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 参考以下示例,将采集到的数据写入文件。 ```js - import fs from '@ohos.file.fs'; - - let state = audioCapturer.state; - // 只有状态为STATE_RUNNING的时候才可以read. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Capturer is not in a correct state to read'); - return; - } - - const path = '/data/data/.pulse_dir/capture_js.wav'; // 采集到的音频文件存储路径 - let file = fs.openSync(filePath, 0o2); - let fd = file.fd; - if (file !== null) { - console.info('AudioRecLog: file created'); - } else { - console.info('AudioRecLog: file create : FAILED'); - return; - } - - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - let numBuffersToCapture = 150; // 循环写入150次 - let count = 0; - while (numBuffersToCapture) { - let bufferSize = await audioCapturer.getBufferSize(); - let buffer = await audioCapturer.read(bufferSize, true); - let options = { - offset: count * this.bufferSize, - length: this.bufferSize + async readData(){ + let state = this.audioCapturer.state; + // 只有状态为STATE_RUNNING的时候才可以read. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Capturer is not in a correct state to read'); + return; } - if (typeof(buffer) == undefined) { - console.info('AudioRecLog: read buffer failed'); + const path = '/data/data/.pulse_dir/capture_js.wav'; // 采集到的音频文件存储路径 + let file = fs.openSync(path, 0o2); + let fd = file.fd; + if (file !== null) { + console.info('AudioRecLog: file created'); } else { - let number = fs.writeSync(fd, buffer, options); - console.info(`AudioRecLog: data written: ${number}`); - } - numBuffersToCapture--; - count++; + console.info('AudioRecLog: file create : FAILED'); + return; + } + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + let numBuffersToCapture = 150; // 循环写入150次 + let count = 0; + while (numBuffersToCapture) { + this.bufferSize = await this.audioCapturer.getBufferSize(); + let buffer = await this.audioCapturer.read(this.bufferSize, true); + let options = { + offset: count * this.bufferSize, + length: this.bufferSize + } + if (typeof(buffer) == undefined) { + console.info('AudioRecLog: read buffer failed'); + } else { + let number = fs.writeSync(fd, buffer, options); + console.info(`AudioRecLog: data written: ${number}`); + } + numBuffersToCapture--; + count++; + } } ``` 4. 采集完成后,调用stop方法,停止录制。 ```js - async function StopCapturer() { - let state = audioCapturer.state; - // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 - if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { - console.info('AudioRecLog: Capturer is not running or paused'); - return; - } - - await audioCapturer.stop(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.error('AudioRecLog: Capturer stop failed'); - } - } + async StopCapturer() { + let state = this.audioCapturer.state; + // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('AudioRecLog: Capturer is not running or paused'); + return; + } + + await this.audioCapturer.stop(); + + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.error('AudioRecLog: Capturer stop failed'); + } + } ``` 5. 任务结束,调用release()方法释放相关资源。 ```js - async function releaseCapturer() { - let state = audioCapturer.state; - // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('AudioRecLog: Capturer already released'); - return; - } - - await audioCapturer.release(); - - state = audioCapturer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } - } + async releaseCapturer() { + let state = this.audioCapturer.state; + // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('AudioRecLog: Capturer already released'); + return; + } + + await this.audioCapturer.release(); + + state = this.audioCapturer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + } ``` 6. (可选)获取采集器相关信息 @@ -178,23 +180,20 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 通过以下代码,可以获取采集器的相关信息。 ```js - // 获取当前采集器状态 - let state = audioCapturer.state; - - // 获取采集器信息 - let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); - - // 获取音频流信息 - let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); - - // 获取音频流ID - let audioStreamId : number = await audioCapturer.getAudioStreamId(); - - // 获取纳秒形式的Unix时间戳 - let audioTime : number = await audioCapturer.getAudioTime(); - - // 获取合理的最小缓冲区大小 - let bufferSize : number = await audioCapturer.getBufferSize(); + async getAudioCapturerInfo(){ + // 获取当前采集器状态 + let state = this.audioCapturer.state; + // 获取采集器信息 + let audioCapturerInfo : audio.AudioCapturerInfo = await this.audioCapturer.getCapturerInfo(); + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await this.audioCapturer.getStreamInfo(); + // 获取音频流ID + let audioStreamId : number = await this.audioCapturer.getAudioStreamId(); + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await this.audioCapturer.getAudioTime(); + // 获取合理的最小缓冲区大小 + let bufferSize : number = await this.audioCapturer.getBufferSize(); + } ``` 7. (可选)使用on('markReach')方法订阅采集器标记到达事件,使用off('markReach')取消订阅事件。 @@ -202,12 +201,13 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 注册markReach监听后,当采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 ```js - audioCapturer.on('markReach', (reachNumber) => { - console.info('Mark reach event Received'); - console.info(`The Capturer reached frame: ${reachNumber}`); - }); - - audioCapturer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + async markReach(){ + this.audioCapturer.on('markReach', 10, (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The Capturer reached frame: ${reachNumber}`); + }); + this.audioCapturer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + } ``` 8. (可选)使用on('periodReach')方法订阅采集器区间标记到达事件,使用off('periodReach')取消订阅事件。 @@ -215,40 +215,43 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 注册periodReach监听后,**每当**采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 ```js - audioCapturer.on('periodReach', (reachNumber) => { - console.info('Period reach event Received'); - console.info(`In this period, the Capturer reached frame: ${reachNumber}`); - }); - - audioCapturer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + async periodReach(){ + this.audioCapturer.on('periodReach', 10, (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the Capturer reached frame: ${reachNumber}`); + }); + this.audioCapturer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + } ``` 9. 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件,当采集器状态更新时,会受到一个包含有事件类型的回调。 ```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; - } - }); + async stateChange(){ + this.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; + } + }); + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-renderer.md b/zh-cn/application-dev/media/audio-renderer.md index c99137e34763e598fa687cd7211870d2432a2c98..0f9436fc3b7d9e015d71869dc9739e7f5124e154 100644 --- a/zh-cn/application-dev/media/audio-renderer.md +++ b/zh-cn/application-dev/media/audio-renderer.md @@ -28,47 +28,59 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 详细API含义可参考:[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8) -1. 使用createAudioRenderer()创建一个AudioRenderer实例。 +1. 使用createAudioRenderer()创建一个全局的AudioRenderer实例,以便后续步骤使用。 在audioRendererOptions中设置相关参数。该实例可用于音频渲染、控制和获取渲染状态,以及注册通知回调。 ```js - import audio from '@ohos.multimedia.audio'; - - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - let audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 - } - let audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); - console.log("Create audio renderer success."); + import audio from '@ohos.multimedia.audio'; + import fs from '@ohos.file.fs'; + + //音频渲染相关接口自测试 + @Entry + @Component + struct AudioRenderer1129 { + private audioRenderer: audio.AudioRenderer; + private bufferSize;//便于步骤3 write函数调用使用 + private audioRenderer1: audio.AudioRenderer; //便于步骤14 完整示例调用使用 + private audioRenderer2: audio.AudioRenderer; //便于步骤14 完整示例调用使用 + + async initAudioRender(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + this.audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + console.log("Create audio renderer success."); + } + } ``` 2. 调用start()方法来启动/恢复播放任务。 ```js - async function startRenderer() { - let state = audioRenderer.state; + async startRenderer() { + let state = this.audioRenderer.state; // Renderer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && - state != audio.AudioState.STATE_STOPPED) { + state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - - await audioRenderer.start(); - - state = audioRenderer.state; + + await this.audioRenderer.start(); + + state = this.audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); } else { @@ -81,111 +93,97 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 3. 调用write()方法向缓冲区写入数据。 - 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 + 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。请注意引入“import fs from '@ohos.file.fs';”,具体请参考步骤1。 ```js - import fs from '@ohos.file.fs'; - import audio from '@ohos.multimedia.audio'; - - async function writeBuffer(buf) { - // 写入数据时,渲染器的状态必须为STATE_RUNNING - if (audioRenderer.state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - 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'); - } - } - - // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) - const bufferSize = await audioRenderer.getBufferSize(); - let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 - const filePath = dir + '/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav - console.info(`file filePath: ${ filePath}`); - - let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); - let stat = await fs.stat(filePath); //音乐文件信息 - let buf = new ArrayBuffer(bufferSize); - let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - for (let i = 0;i < len; i++) { - let options = { - offset: i * this.bufferSize, - length: this.bufferSize - } - let readsize = await fs.read(file.fd, buf, options) - let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer.write(buf,(err,writeSize)=>{ - if(err){ - reject(err) - }else{ - resolve(writeSize) - } + async writeData(){ + // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + this.bufferSize = await this.audioRenderer.getBufferSize(); + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const filePath = dir + '/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav + console.info(`file filePath: ${ filePath}`); + + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + let stat = await fs.stat(filePath); //音乐文件信息 + let buf = new ArrayBuffer(this.bufferSize); + let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); + for (let i = 0;i < len; i++) { + let options = { + offset: i * this.bufferSize, + length: this.bufferSize + } + let readsize = await fs.read(file.fd, buf, options) + let writeSize = await new Promise((resolve,reject)=>{ + this.audioRenderer.write(buf,(err,writeSize)=>{ + if(err){ + reject(err) + }else{ + resolve(writeSize) + } + }) }) - }) + } + + fs.close(file) + await this.audioRenderer.stop(); //停止渲染 + await this.audioRenderer.release(); //释放资源 } - - fs.close(file) - await audioRenderer.stop(); //停止渲染 - await audioRenderer.release(); //释放资源 ``` 4. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 ```js - async function pauseRenderer() { - let state = audioRenderer.state; - // 只有渲染器状态为STATE_RUNNING的时候才能暂停 - 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() { - let state = audioRenderer.state; - // 只有渲染器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 - 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 pauseRenderer() { + let state = this.audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能暂停 + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await this.audioRenderer.pause(); + + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async stopRenderer() { + let state = this.audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await this.audioRenderer.stop(); + + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } ``` 5. (可选)调用drain()方法清空缓冲区。 ```js - async function drainRenderer() { - let state = audioRenderer.state; - // 只有渲染器状态为STATE_RUNNING的时候才能使用drain() - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.drain(); - state = audioRenderer.state; + async drainRenderer() { + let state = this.audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能使用drain() + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; } + + await this.audioRenderer.drain(); + state = this.audioRenderer.state; + } ``` 6. 任务完成,调用release()方法释放相关资源。 @@ -193,22 +191,22 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 ```js - async function releaseRenderer() { - let state = audioRenderer.state; - // 渲染器状态不是STATE_RELEASED或STATE_NEW状态,才能release - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('Renderer already released'); - return; - } - await audioRenderer.release(); + async releaseRenderer() { + let state = this.audioRenderer.state; + // 渲染器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('Renderer already released'); + return; + } + await this.audioRenderer.release(); - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } + state = this.audioRenderer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); } + } ``` 7. (可选)获取渲染器相关信息 @@ -216,26 +214,22 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 通过以下代码,可以获取渲染器的相关信息。 ```js - // 获取当前渲染器状态 - let state = audioRenderer.state; - - // 获取渲染器信息 - let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo(); - - // 获取音频流信息 - let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo(); - - // 获取音频流ID - let audioStreamId : number = await audioRenderer.getAudioStreamId(); - - // 获取纳秒形式的Unix时间戳 - let audioTime : number = await audioRenderer.getAudioTime(); - - // 获取合理的最小缓冲区大小 - let bufferSize : number = await audioRenderer.getBufferSize(); - - // 获取渲染速率 - let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); + async getRenderInfo(){ + // 获取当前渲染器状态 + let state = this.audioRenderer.state; + // 获取渲染器信息 + let audioRendererInfo : audio.AudioRendererInfo = await this.audioRenderer.getRendererInfo(); + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await this.audioRenderer.getStreamInfo(); + // 获取音频流ID + let audioStreamId : number = await this.audioRenderer.getAudioStreamId(); + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await this.audioRenderer.getAudioTime(); + // 获取合理的最小缓冲区大小 + let bufferSize : number = await this.audioRenderer.getBufferSize(); + // 获取渲染速率 + let renderRate : audio.AudioRendererRate = await this.audioRenderer.getRenderRate(); + } ``` 8. (可选)设置渲染器相关信息 @@ -243,17 +237,17 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 通过以下代码,可以设置渲染器的相关信息。 ```js - // 设置渲染速率为正常速度 - let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; - await audioRenderer.setRenderRate(renderRate); - - // 设置渲染器音频中断模式为SHARE_MODE - let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; - await audioRenderer.setInterruptMode(interruptMode); - - // 设置一个流的音量为0.5 - let volume : number = 0.5; - await audioRenderer.setVolume(volume); + async setAudioRenderInfo(){ + // 设置渲染速率为正常速度 + let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; + await this.audioRenderer.setRenderRate(renderRate); + // 设置渲染器音频中断模式为SHARE_MODE + let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; + await this.audioRenderer.setInterruptMode(interruptMode); + // 设置一个流的音量为0.5 + let volume : number = 0.5; + await this.audioRenderer.setVolume(volume); + } ``` 9. (可选)使用on('audioInterrupt')方法订阅渲染器音频中断事件,使用off('audioInterrupt')取消订阅事件。 @@ -267,45 +261,45 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 需要说明的是,本模块的订阅音频中断事件与[AudioManager](../reference/apis/js-apis-audio.md#audiomanager)模块中的on('interrupt')稍有不同。自api9以来,on('interrupt')和off('interrupt')均被废弃。在AudioRenderer模块,当开发者需要监听焦点变化事件时,只需要调用on('audioInterrupt')函数,当应用内部的AudioRenderer对象在start\stop\pause等动作发生时,会主动请求焦点,从而发生焦点转移,相关的AudioRenderer对象即可获取到对应的回调信息。但对除AudioRenderer的其他对象,例如FM、语音唤醒等,应用不会创建对象,此时可调用AudioManager中的on('interrupt')获取焦点变化通知。 ```js - audioRenderer.on('audioInterrupt', (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) { + async subscribeAudioRender(){ + this.audioRenderer.on('audioInterrupt', (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) { // 音频框架发起的强制暂停操作,为防止数据丢失,此时应该停止数据的写操作 - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('isPlay is false'); + break; // 音频框架发起的强制停止操作,为防止数据丢失,此时应该停止数据的写操作 - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('isPlay is false'); + break; // 音频框架发起的强制降低音量操作 - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; // 音频框架发起的恢复音量操作 - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { // 提醒App开始渲染 - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + this.startRenderer(); + break; // 提醒App音频流被中断,由App自主决定是否继续(此处选择暂停) - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('isPlay is false'); + this.pauseRenderer(); + break; + } } - } - }); - - audioRenderer.off('audioInterrupt'); // 取消音频中断事件的订阅,后续将无法监听到音频中断事件 + }); + } ``` 10. (可选)使用on('markReach')方法订阅渲染器标记到达事件,使用off('markReach')取消订阅事件。 @@ -313,12 +307,14 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 注册markReach监听后,当渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 ```js - audioRenderer.on('markReach', (reachNumber) => { - console.info('Mark reach event Received'); - console.info(`The renderer reached frame: ${reachNumber}`); - }); - - audioRenderer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + async markReach(){ + this.audioRenderer.on('markReach', 50, (position) => { + if (position == 50) { + console.info('ON Triggered successfully'); + } + }); + this.audioRenderer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + } ``` 11. (可选)使用on('periodReach')方法订阅渲染器区间标记到达事件,使用off('periodReach')取消订阅事件。 @@ -326,12 +322,13 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 注册periodReach监听后,**每当**渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 ```js - audioRenderer.on('periodReach', (reachNumber) => { - console.info('Period reach event Received'); - console.info(`In this period, the renderer reached frame: ${reachNumber} `); - }); - - audioRenderer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + async periodReach(){ + this.audioRenderer.on('periodReach',10, (reachNumber) => { + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); + + this.audioRenderer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + } ``` 12. (可选)使用on('stateChange')方法订阅渲染器音频状态变化事件。 @@ -339,10 +336,12 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 注册stateChange监听后,当渲染器的状态发生改变时,会触发回调并返回当前渲染器的状态。 ```js - audioRenderer.on('stateChange', (audioState) => { - console.info('State change event Received'); - console.info(`Current renderer state is: ${audioState}`); - }); + async stateChange(){ + this.audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + } ``` 13. (可选)对on()方法的异常处理。 @@ -350,21 +349,24 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 在使用on()方法时,如果传入的字符串错误或传入的参数类型错误,程序会抛出异常,需要用try catch来捕获。 ```js - try { - audioRenderer.on('invalidInput', () => { // 字符串不匹配 - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // 程序抛出401异常 - } - try { - audioRenderer.on(1, () => { // 入参类型错误 - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // 程序抛出6800101异常 + async errorCall(){ + try { + this.audioRenderer.on('invalidInput', () => { // 字符串不匹配 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出401异常 + } + try { + this.audioRenderer.on(1, () => { // 入参类型错误 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出6800101异常 + } } ``` 14. (可选)on('audioInterrupt')方法完整示例。 + 请注意:在调用前声明audioRenderer1与audioRenderer2对象,具体请参考步骤1。 同一个应用中的AudioRender1和AudioRender2在创建时均设置了焦点模式为独立,并且调用on('audioInterrupt')监听焦点变化。刚开始AudioRender1拥有焦点,当AudioRender2获取到焦点时,audioRenderer1将收到焦点转移的通知,打印相关日志。如果AudioRender1和AudioRender2不将焦点模式设置为独立,则监听处理中的日志在应用运行过程中永远不会被打印。 ```js async runningAudioRender1(){ @@ -383,31 +385,31 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } - + //1.1 创建对象 - audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); + this.audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); console.info("Create audio renderer 1 success."); - + //1.2 设置焦点模式为独立模式 :1 - audioRenderer1.setInterruptMode(1).then( data => { + this.audioRenderer1.setInterruptMode(1).then( data => { console.info('audioRenderer1 setInterruptMode Success!'); }).catch((err) => { console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); }); - + //1.3 设置监听 - audioRenderer1.on('audioInterrupt', async(interruptEvent) => { + this.audioRenderer1.on('audioInterrupt', async(interruptEvent) => { console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) }); - + //1.4 启动渲染 - await audioRenderer1.start(); + await this.audioRenderer1.start(); console.info('startAudioRender1 success'); - + //1.5 获取缓存区大小,此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) - const bufferSize = await audioRenderer1.getBufferSize(); + const bufferSize = await this.audioRenderer1.getBufferSize(); console.info(`audio bufferSize: ${bufferSize}`); - + //1.6 获取原始音频数据文件 let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 const path1 = dir + '/music001_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav @@ -416,14 +418,14 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 let stat = await fs.stat(path1); //音乐文件信息 let buf = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - + //1.7 通过audioRender对缓存区的原始音频数据进行渲染 for (let i = 0;i < len; i++) { let options = { offset: i * this.bufferSize, length: this.bufferSize } - let readsize = await fs.read(file.fd, buf, options) + let readsize = await fs.read(file1.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ this.audioRenderer1.write(buf,(err,writeSize)=>{ if(err){ @@ -432,13 +434,13 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 resolve(writeSize) } }) - }) + }) } fs.close(file1) - await audioRenderer1.stop(); //停止渲染 - await audioRenderer1.release(); //释放资源 + await this.audioRenderer1.stop(); //停止渲染 + await this.audioRenderer1.release(); //释放资源 } - + async runningAudioRender2(){ let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, @@ -455,31 +457,31 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } - + //2.1 创建对象 - audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); + this.audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); console.info("Create audio renderer 2 success."); - + //2.2 设置焦点模式为独立模式 :1 - audioRenderer2.setInterruptMode(1).then( data => { + this.audioRenderer2.setInterruptMode(1).then( data => { console.info('audioRenderer2 setInterruptMode Success!'); }).catch((err) => { console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); }); - + //2.3 设置监听 - audioRenderer2.on('audioInterrupt', async(interruptEvent) => { + this.audioRenderer2.on('audioInterrupt', async(interruptEvent) => { console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) }); - + //2.4 启动渲染 - await audioRenderer2.start(); + await this.audioRenderer2.start(); console.info('startAudioRender2 success'); - + //2.5 获取缓存区大小 - const bufferSize = await audioRenderer2.getBufferSize(); + const bufferSize = await this.audioRenderer2.getBufferSize(); console.info(`audio bufferSize: ${bufferSize}`); - + //2.6 获取原始音频数据文件 let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 const path2 = dir + '/music002_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav @@ -488,14 +490,14 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 let stat = await fs.stat(path2); //音乐文件信息 let buf = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - + //2.7 通过audioRender对缓存区的原始音频数据进行渲染 for (let i = 0;i < len; i++) { let options = { offset: i * this.bufferSize, length: this.bufferSize } - let readsize = await fs.read(file.fd, buf, options) + let readsize = await fs.read(file2.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ this.audioRenderer2.write(buf,(err,writeSize)=>{ if(err){ @@ -504,28 +506,17 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 resolve(writeSize) } }) - }) + }) } fs.close(file2) - await audioRenderer2.stop(); //停止渲染 - await audioRenderer2.release(); //释放资源 + await this.audioRenderer2.stop(); //停止渲染 + await this.audioRenderer2.release(); //释放资源 } - - async writeBuffer(buf, audioRender) { - let writtenbytes; - await audioRender.write(buf).then((value) => { - writtenbytes = value; - console.info(`Actual written bytes: ${writtenbytes} `); - }); - if (typeof(writtenbytes) != 'number' || writtenbytes < 0) { - console.error('get Write buffer failed. check the state of renderer'); - } - } - + //综合调用入口 async test(){ - await runningAudioRender1(); - await runningAudioRender2(); + await this.runningAudioRender1(); + await this.runningAudioRender2(); } - + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/avplayer-playback.md b/zh-cn/application-dev/media/avplayer-playback.md index 950ccd19857cd5704b86d82828c522e45ddde4aa..760064f23a825a03c0de41737d84f91760ec2b3d 100644 --- a/zh-cn/application-dev/media/avplayer-playback.md +++ b/zh-cn/application-dev/media/avplayer-playback.md @@ -299,13 +299,13 @@ export class AVPlayerDemo { async avPlayerDemo() { // 创建avPlayer实例对象 this.avPlayer = await media.createAVPlayer() - let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 - // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 - let path = pathDir + '/H264_AAC.mp4' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - this.avPlayer.url = fdPath + let fileDescriptor = undefined + // 使用资源管理模块的getRawFileDescriptor获取集成在应用中的媒体资源,并使用AVPlayer的fdSrc属性完成媒体资源初始化 + // 其中的参数fd/offset/length定义请查看媒体API文档,globalThis.abilityContext参数为系统环境变量,在系统启动时在主界面保存为全局变量 + await globalThis.abilityContext.resourceManager.getRawFileDescriptor('H264_AAC.mp4').then((value) => { + fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length} + }) + this.avPlayer.fdSrc = fileDescriptor } } ``` diff --git a/zh-cn/application-dev/media/opensles-capture.md b/zh-cn/application-dev/media/opensles-capture.md index 4c9a88531543ba15f882720fe83e512373496c2c..bf7120054a8431a0ccbe877a312d44dbd80f33e6 100644 --- a/zh-cn/application-dev/media/opensles-capture.md +++ b/zh-cn/application-dev/media/opensles-capture.md @@ -51,12 +51,12 @@ 3 }; - //具体参数需要根据音频文件格式进行适配 + // 具体参数需要根据音频文件格式进行适配 SLDataFormat_PCM format_pcm = { - SL_DATAFORMAT_PCM, - OHOS::AudioStandard::AudioChannel::MONO, - OHOS::AudioStandard::AudioSamplingRate::SAMPLE_RATE_44100, - OHOS::AudioStandard::AudioSampleFormat::SAMPLE_S16LE, + SL_DATAFORMAT_PCM, // 输入的音频格式 + 1, // 单声道 + SL_SAMPLINGRATE_44_1, // 采样率,44100HZ + SL_PCMSAMPLEFORMAT_FIXED_16, // 音频采样格式,小尾数,带符号的16位整数 0, 0, 0 @@ -107,7 +107,7 @@ return; } - //wavFile_ 需要设置为用户想要录音的文件描述符 + // wavFile_ 需要设置为用户想要录音的文件描述符 (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); ``` diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index 82996bf0813c9e9d640bec4dd9fa5fbb2fe81510..34d3bb66aa5367e975ea54ff28d803b54953f79e 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -11,7 +11,6 @@ - 应用程序包结构 - [Stage模型应用程序包结构](application-package-structure-stage.md) - [FA模型应用程序包结构](application-package-structure-fa.md) - - [HAR包结构](har-structure.md) - 应用程序包多HAP机制 - [多HAP机制设计目标](multi-hap-objective.md) - [多HAP构建视图](multi-hap-build-view.md) @@ -20,6 +19,12 @@ - [多HAP运行机制及数据通信方式](multi-hap-principles.md) - [应用程序包安装和卸载流程](application-package-install-uninstall.md) - [应用程序包更新流程](application-package-update.md) + - 共享包 + - [共享包概述](shared-guide.md) + - [HAR](har-package.md) + - HSP + - [应用内HSP开发指导](in-app-hsp.md) + - [应用间HSP开发指导(仅对系统应用开放)](cross-app-hsp.md) - 应用程序包快速修复 - [快速修复概述](quickfix-principles.md) - [快速修复调试指导](quickfix-debug.md) diff --git a/zh-cn/application-dev/quick-start/application-package-structure-stage.md b/zh-cn/application-dev/quick-start/application-package-structure-stage.md index b484f0ab579c178fd2e1dd0a62452ee54c0e2157..41c5bc2431533a746a6367d2a90fa64809036ded 100644 --- a/zh-cn/application-dev/quick-start/application-package-structure-stage.md +++ b/zh-cn/application-dev/quick-start/application-package-structure-stage.md @@ -4,7 +4,7 @@ 基于[Stage模型](application-configuration-file-overview-stage.md)开发的应用,经编译打包后,其应用程序包结构如下图**应用程序包结构(Stage模型)**所示。开发者需要熟悉应用程序包结构相关的基本概念。 -- 在开发态,一个应用包含一个或者多个Module,可以在[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio/)工程中[创建一个或者多个Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3)。Module是OpenHarmony应用/服务的基本功能单元,包含了源代码、资源文件、第三方库及应用/服务配置文件,每一个Module都可以独立进行编译和运行。Module分为“Ability”和“Library”两种类型,“Ability”类型的Module对应于编译后的HAP(Harmony Ability Package);“Library”类型的Module对应于[HAR](har-structure.md)(Harmony Ability Resources)包,即编译后的.tgz文件。 +- 在开发态,一个应用包含一个或者多个Module,可以在[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio/)工程中[创建一个或者多个Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3)。Module是OpenHarmony应用/服务的基本功能单元,包含了源代码、资源文件、第三方库及应用/服务配置文件,每一个Module都可以独立进行编译和运行。Module分为“Ability”和“Library”两种类型,“Ability”类型的Module对应于编译后的HAP(Harmony Ability Package);“Library”类型的Module对应于[HAR](har-package.md)(Harmony Archive),或者[HSP](shared-guide.md)(Harmony Shared Package)。 一个Module可以包含一个或多个[UIAbility](../application-models/uiability-overview.md)组件,如**Module与UIAbility组件关系示意图**所示。 **图1** Module与UIAbility组件关系示意图 diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md index b9cc90f0b09ef277437451bdcd5a7b87daf54949..1d1635674d5e913a1a4ac33c84e2a165e092df5d 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -42,6 +42,8 @@ ForEach( ) ``` +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -254,7 +256,7 @@ struct MyComponent { this.data.pushData('/path/image' + this.data.totalCount() + '.png') }) }, item => item) - } + }.height('100%').width('100%') } } ``` diff --git a/zh-cn/application-dev/quick-start/cross-app-hsp.md b/zh-cn/application-dev/quick-start/cross-app-hsp.md index 8b9d5f8832629a6d19659f027b9476ad45397cdd..91a8972480dc84591d93ed4284243b342eaf7aa5 100644 --- a/zh-cn/application-dev/quick-start/cross-app-hsp.md +++ b/zh-cn/application-dev/quick-start/cross-app-hsp.md @@ -1,17 +1,23 @@ # 应用间HSP开发指导 应用间`HSP`用于不同应用间的代码、资源共享。 -应用间`HSP`的宿主应用是一种特殊状态的应用,只能由一个[HSP](hsp-guide.md)包组成,不会独立运行在设备上,而是被普通应用模块的依赖项引用。当普通应用运行时,通过动态调用的方式使用应用间`HSP`提供的能力,从而实现应用自身所需要的功能。 +应用间`HSP`的宿主应用是一种特殊状态的应用,只能由一个`HSP`组成,不会独立运行在设备上,而是被普通应用模块的依赖项引用。当普通应用运行时,通过动态调用的方式使用应用间`HSP`提供的能力,从而实现应用自身所需要的功能。 + +## 注意事项 +1. 应用间`HSP`的代码会运行再开发者应用的进程中,调用相关代码时,需要做好异常捕获与容错处理,防止由于应用间`HSP`功能异常导致的稳定性问题。 +2. 一个应用可以同时依赖多个应用间`HSP`。 +3. 应用间`HSP`会影响开发者应用自身的启动时间,依赖过多的应用间`HSP`可能会导致启动时延发生明显的劣化,建议将依赖的数目控制在16个以内。 +4. 当前三方开发者开发者只能使用系统提供的应用间`HSP`,不支持开发并发布自己的应用间`HSP`。 ## 应用间HSP的使用 应用间HSP会分为两部分对外发布: -一部分为[HAR包](har-package.md),这部分`HAR`包中不会包含具体的功能实现代码,而仅仅包含导出的对象与方法,所以体积很小。应用开发者将`HAR`包集成到自身的工程中,然后就可以通过调用`HAR`包中提供的对象与方法完成自身的应用功能。 +一部分为[HAR](har-package.md),这部分`HAR`中不会包含具体的功能实现代码,而仅仅包含导出的对象与方法,所以体积很小。应用开发者将`HAR`集成到自身的工程中,然后就可以通过调用`HAR`中提供的对象与方法完成自身的应用功能。 -另外一部分为[HSP](hsp-guide.md),这部分为应用间`HSP`的具体实现,里面包含js/ts代码、C++库、资源和配置文件。这部分会上架到应用市场或者集成到系统版本中。 +另外一部分为HSP,这部分为应用间`HSP`的具体实现,里面包含js/ts代码、C++库、资源和配置文件。这部分会上架到应用市场或者集成到系统版本中。 -### 集成应用间HSP的HAR包 -`HAR`包中的`index.d.ets`文件是应用间`HSP`导出的声明文件的入口,所有需要导出的接口,统一在`index.d.ets`文件中定义。`index.d.ets`文件路径如下: +### 集成应用间HSP的HAR +`HAR`中的`index.d.ets`文件是应用间`HSP`导出的声明文件的入口,所有需要导出的接口,统一在`index.d.ets`文件中定义。`index.d.ets`文件路径如下: ``` src ├── main @@ -110,8 +116,8 @@ extern "C" __attribute__((constructor)) void RegisterLibaModule(void) { napi_module_register(&demoModule); } ``` -### 使用HAR包导出的能力 -引用`HAR`包前,需要先配置对`HAR`的依赖,配置方式可参考[文档](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391)。`HAR`包配置成功后,在配置模块的`module.json`中会生成相关依赖项信息,如下所示: +### 使用HAR导出的能力 +引用`HAR`前,需要先配置对`HAR`的依赖,配置方式可参考[文档](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391)。`HAR`配置成功后,在配置模块的`module.json`中会生成相关依赖项信息,如下所示: ```json "dependencies": [ { @@ -122,8 +128,8 @@ extern "C" __attribute__((constructor)) void RegisterLibaModule(void) { ] ``` 其中`bundleName`为应用间`HSP`的`bundle`名称,`moduleName`为应用间`HSP`的模块名称,`versionCode`为应用间`HSP`的版本号。 -#### **使用HAR包中的ArkUI组件** -`HAR`共享包的依赖配置成功后,可以引用`HAR`共享包的ArkUI组件。ArkUI组件的导入方式与ts的导入方式一致,通过`import`引入`HAR`共享包导出的ArkUI组件,示例如下所示: +#### **使用HAR中的ArkUI组件** +`HAR`的依赖配置成功后,可以引用`HAR`的ArkUI组件。ArkUI组件的导入方式与ts的导入方式一致,通过`import`引入`HAR`导出的ArkUI组件,示例如下所示: ``` ts import { UIComponent } from 'liba' @@ -133,7 +139,7 @@ struct Index { @State message: string = 'Hello World' build() { Row() { - // 引用HAR共享包的ArkUI组件 + // 引用HAR的ArkUI组件 UIComponent() Column() { Text(this.message) @@ -147,8 +153,8 @@ struct Index { } ``` -#### **使用HAR包中的ts方法** -通过`import`引用`HAR`共享包导出的ts类和方法,示例如下所示: +#### **使用HAR中的ts方法** +通过`import`引用`HAR`导出的ts类和方法,示例如下所示: ``` ts import { foo1 } from 'liba' import { foo2 } from 'liba' @@ -160,7 +166,7 @@ struct Index { Column() { Button('Button') .onClick(()=>{ - // 引用HAR共享包的ts方法 + // 引用HAR的ts方法 foo1(); foo2(); }) @@ -171,8 +177,8 @@ struct Index { } } ``` -#### **使用HAR包中的native方法** -通过`import`引用`HAR`共享包导出的native方法,示例如下所示: +#### **使用HAR中的native方法** +通过`import`引用`HAR`导出的native方法,示例如下所示: ``` ts import { nativeHello } from 'liba' @@ -183,7 +189,7 @@ struct Index { Column() { Button('Button') .onClick(()=>{ - // 引用HAR共享包的native方法 + // 引用HAR的native方法 nativeHello(); }) } @@ -196,26 +202,20 @@ struct Index { ## 应用间HSP的分发方式 应用间`HSP`由于并未直接完整的集成到开发者应用中去,所以需要提前预置在系统版本中或者随开发者应用同步安装到设备上,主要有以下两种形式: -1. 随系统发布,部分常用应用间`HSP`会预置在系统版本中 +1. 随系统发布,部分常用应用间`HSP`会预置在系统版本中。 2. 随应用发布,即用户在应用市场下载应用时,如果应用依赖了一个或者多个应用间`HSP`,同时设备上没有安装这个其依赖的应用间`HSP`时,应用市场会为用户同时下载普通应用以及其依赖的应用间`HSP`。从而保证普通应用能够正常使用共享库的功能。 ### 应用间HSP的调试方式 开发者本地调试应用间`HSP`相关的功能时,可能并不具备上述分发的条件,此时可以通过`bm`相关指令本地完成应用间`HSP`的分发,主要步骤如下: -1. 获取到应用间`HSP`的安装包 -2. 通过`bm`指令先安装应用间`HSP`的安装包 +1. 获取到应用间`HSP`的安装包。 +2. 通过`bm`指令先安装应用间`HSP`的安装包。 ``` bm install -s sharebundle.hsp ``` -3. 通过`bm`指令后安装开发者自身的应用`hap` +3. 通过`bm`指令后安装开发者自身的应用`hap`。 ``` bm install -p feature.hap ``` -4. 启动开发者自身的应用,调试相关功能 +4. 启动开发者自身的应用,调试相关功能。 -**注意**:步骤2和步骤3不可以颠倒,否则会由于缺少必要的应用间`HSP`导致开发者的应用安装失败。更多`bm`相关指令可以参考[文档](https://gitee.com/openharmony/bundlemanager_bundle_framework#bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)。 - -## 注意事项 -1. 应用间`HSP`的代码会运行再开发者应用的进程中,调用相关代码时,需要做好异常捕获与容错处理,防止由于应用间`HSP`功能异常导致的稳定性问题 -2. 一个应用可以同时依赖多个应用间`HSP` -3. 应用间`HSP`会影响开发者应用自身的启动时间,依赖过多的应用间HSP可能会导致启动时延发生明显的劣化,建议将依赖的数目控制在16个以内。 -4. 当前三方开发者开发者只能使用系统提供的应用间`HSP`,不支持开发并发布自己的应用间`HSP`。 \ No newline at end of file +**注意**:步骤2和步骤3不可以颠倒,否则会由于缺少必要的应用间`HSP`导致开发者的应用安装失败。更多`bm`相关指令可以参考[文档](https://gitee.com/openharmony/bundlemanager_bundle_framework#bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)。 \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md b/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md index 655446886bf5dc1d872927cd0c07b35634a5716e..4d53d2d7be083d5d8d15cb7168de4f9bfdde242b 100644 --- a/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md +++ b/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md @@ -22,7 +22,7 @@ 4. 编译:./build.sh --product-name ohos-sdk -编译成功后导出即可 +编译成功后导出out/sdk/packages/ohos-sdk/目录下的文件即可 ## 替换SDK diff --git a/zh-cn/application-dev/quick-start/har-package.md b/zh-cn/application-dev/quick-start/har-package.md index ed82cdf4949b6946feab4f462655346dca070223..88e4c47a32bf2d7fe0162c177ae638ef12ee053a 100644 --- a/zh-cn/application-dev/quick-start/har-package.md +++ b/zh-cn/application-dev/quick-start/har-package.md @@ -1,8 +1,8 @@ # HAR -HAR(Harmony Archive)是Harmony静态共享包,可以包含代码、C++库、资源和配置文件。通过HAR共享包,可以实现多个模块或多个工程共享ArkUI组件、资源等相关代码。HAR不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。 +HAR(Harmony Archive)是静态共享包,可以包含代码、C++库、资源和配置文件。通过HAR可以实现多个模块或多个工程共享ArkUI组件、资源等相关代码。HAR不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。 ## 创建HAR模块 -HAR包对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3),可以通过DevEco Studio创建一个HAR模块。HAR模块默认不开启混淆能力,开启混淆能力,需要把HAR模块的build-profile.json5文件中的artifactType字段设置为obfuscation,配置如下所示: +HAR对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3),可以通过DevEco Studio创建一个HAR模块。HAR模块默认不开启混淆能力,开启混淆能力,需要把HAR模块的build-profile.json5文件中的artifactType字段设置为obfuscation,配置如下所示: ```json { @@ -19,7 +19,7 @@ artifactType字段有以下两种取值,默认缺省为original。 需要对代码资产进行保护时,建议开启混淆能力,混淆能力开启后,DevEco Studio在构建HAR时,会对代码进行编译、混淆及压缩处理,保护代码资产。 注意:artifactType字段设置为obfuscation时,apiType字段必须设置为stageMode,因为Stage模型才支持混淆。 -## HAR共享包开发注意事项 +## HAR开发注意事项 - HAR不支持在配置文件中声明abilities、extensionAbilities组件。 - HAR不支持在配置文件中声明pages页面。 - HAR不支持在build-profile.json5文件的buildOption中配置worker。 @@ -27,7 +27,7 @@ artifactType字段有以下两种取值,默认缺省为original。 - Stage模型的HAR,不能引用AppScope内的内容。在编译构建时APPScope中的内容不会打包到HAR中,导致HAR资源引用失败。 ## 导出HAR的ArkUI组件、接口、资源 -index.ets文件是HAR共享包导出声明文件的入口,HAR共享包需要导出的接口,统一在index.ets文件中导出。index.ets文件是DevEco Studio默认自动生成的,用户也可以自定义,在模块的package.json文件中的main字段配置入口声明文件,配置如下所示: +index.ets文件是HAR导出声明文件的入口,HAR需要导出的接口,统一在index.ets文件中导出。index.ets文件是DevEco Studio默认自动生成的,用户也可以自定义,在模块的package.json文件中的main字段配置入口声明文件,配置如下所示: ```json { "main": "index.ets" @@ -84,17 +84,17 @@ export { func } from './src/main/ts/test' export { func2 } from './src/main/ts/test' ``` ### 资源 -HAR模块编译打包时会把资源打包到HAR包中。在编译构建HAP时,DevEco Studio会从HAP模块及依赖的模块中收集资源文件,如果不同模块下的资源文件出现重名冲突时,DevEco Studio会按照以下优先级进行覆盖(优先级由高到低): +HAR模块编译打包时会把资源打包到HAR中。在编译构建HAP时,DevEco Studio会从HAP模块及依赖的模块中收集资源文件,如果不同模块下的资源文件出现重名冲突时,DevEco Studio会按照以下优先级进行覆盖(优先级由高到低): - AppScope(仅API9的Stage模型支持)。 - HAP包自身模块。 - 依赖的HAR模块,如果依赖的多个HAR之间有资源冲突,会按照依赖顺序进行覆盖(依赖顺序在前的优先级较高)。 ## 引用HAR的ArkUI组件、接口、资源 -引用HAR共享包前,需要先配置对HAR的依赖,配置方式可[参考](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391)。 +引用HAR前,需要先配置对HAR的依赖,配置方式可[参考](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391)。 -### 引用HAR共享包的ArkUI组件 +### 引用HAR的ArkUI组件 -HAR共享包的依赖配置成功后,可以引用HAR共享包的ArkUI组件。ArkUI组件的导入方式与ts的导入方式一致,通过`import`引入HAR共享包导出的ArkUI组件,示例如下所示: +HAR的依赖配置成功后,可以引用HAR的ArkUI组件。ArkUI组件的导入方式与ts的导入方式一致,通过`import`引入HAR导出的ArkUI组件,示例如下所示: ```js // entry/src/main/ets/pages/index.ets import { MainPage } from "@ohos/library" @@ -105,7 +105,7 @@ struct Index { @State message: string = 'Hello World' build() { Row() { - // 引用HAR共享包的ArkUI组件 + // 引用HAR的ArkUI组件 MainPage() Column() { Text(this.message) @@ -118,8 +118,8 @@ struct Index { } } ``` -### 引用HAR共享包的类和方法 -通过`import`引用HAR共享包导出的ts类和方法,示例如下所示: +### 引用HAR的类和方法 +通过`import`引用HAR导出的ts类和方法,示例如下所示: ```js // entry/src/main/ets/pages/index.ets import { Log } from "@ohos/library" @@ -133,7 +133,7 @@ struct Index { Column() { Button('Button') .onClick(()=>{ - // 引用HAR共享包的类和方法 + // 引用HAR的类和方法 Log.info("har msg"); func(); }) @@ -144,8 +144,8 @@ struct Index { } } ``` -### 引用HAR共享包的资源 -通过`$r`引用HAR共享包中的资源,例如在HAR模块的`src/main/resources`里添加字符串资源(在string.json中定义,name:hello_har)和图片资源(icon_har.png),然后在Entry模块中引用该字符串和图片资源的示例如下所示: +### 引用HAR的资源 +通过`$r`引用HAR中的资源,例如在HAR模块的`src/main/resources`里添加字符串资源(在string.json中定义,name:hello_har)和图片资源(icon_har.png),然后在Entry模块中引用该字符串和图片资源的示例如下所示: ```js // entry/src/main/ets/pages/index.ets @Entry @@ -154,11 +154,11 @@ struct Index { build() { Row() { Column() { - // 引用HAR共享包的字符串资源 + // 引用HAR的字符串资源 Text($r("app.string.hello_har")) .fontSize(50) .fontWeight(FontWeight.Bold) - // 引用HAR共享包的图片资源 + // 引用HAR的图片资源 Image($r("app.media.icon_har")) } .width('100%') diff --git a/zh-cn/application-dev/quick-start/har-structure.md b/zh-cn/application-dev/quick-start/har-structure.md deleted file mode 100644 index cc154c35d98365155bffb2ee8bb995ef51d69571..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/quick-start/har-structure.md +++ /dev/null @@ -1,9 +0,0 @@ -# HAR包结构 - - -[HAR(Harmony Archive)](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434)是Harmony静态共享包,可以包含代码、C++库、资源和module.json文件(Stage模型)或config.json文件(FA模型)等,用于实现多个模块或多个工程间的代码共享。 - -HAR包不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。 - -HAR包对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3)。 - diff --git a/zh-cn/application-dev/quick-start/hsp-guide.md b/zh-cn/application-dev/quick-start/hsp-guide.md deleted file mode 100644 index e2a5e3cc161ac493652b89bd5240cfb80c4f7bbd..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/quick-start/hsp-guide.md +++ /dev/null @@ -1,18 +0,0 @@ -# HSP概述 - -`HSP`(`Harmony Shared Package`)是Harmony动态共享包,可以包含代码、C++库、资源和配置文件。 -`HSP`与[HAR(Harmony Achive)](har-package.md)都是为了实现代码和资源的共享,最大的不同之处在于,`HAR`中的代码和资源跟随使用方编译,如果有多个使用方,它们的编译产物中会存在多份相同拷贝。**而`HSP`中的代码和资源可以独立编译,运行时在一个进程中代码也只会存在一份。** - -**图1** `HAR`和`HSP`在`APP`包中的形态示意图 -![in-app-hsp-har](figures/in-app-hsp-har.png) - -**HSP旨在解决HAR包存在的几个问题:** -- 多个`HAP`引用相同`HAR`包,导致的`APP`包大小膨胀问题 -- 多个`HAP`引用相同`HAR`包,`HAR`包中的一些状态变量无法共享的问题 - -**HSP的一些约束:** -- `HSP`及其使用方都必须是`Stage`模型 -- `HSP`及其使用方都必须使用`esmodule`编译模式 -- `HSP`不支持在配置文件中声明`abilities`、`extensionAbilities`标签 - -`HSP`按照使用场景可以分为[应用内HSP](in-app-hsp.md)和[应用间HSP](cross-app-hsp.md)。它们在配置文件和使用方式等方面有所区别。 \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/in-app-hsp.md b/zh-cn/application-dev/quick-start/in-app-hsp.md index 2c456b608da986d0063c5821f6a515ec13e69761..177700e909363128a4df4da45de0e1d7c56f36f8 100644 --- a/zh-cn/application-dev/quick-start/in-app-hsp.md +++ b/zh-cn/application-dev/quick-start/in-app-hsp.md @@ -110,7 +110,7 @@ export { nativeMulti } from './utils/nativeTest' "library": "file:../library" } ``` -然后就可以像使用`HAR`包一样调用`HSP`的对外接口了。 +然后就可以像使用`HAR`一样调用`HSP`的对外接口了。 例如,上面的`library`已经导出了下面这些接口: ```ts // library/src/main/ets/index.ets diff --git a/zh-cn/application-dev/quick-start/module-configuration-file.md b/zh-cn/application-dev/quick-start/module-configuration-file.md index dbd64ee433a13647d1cf022a1c0c3984fd6afed3..d1524a70ba9a993d1cc5e8c83a2f347c4106e656 100644 --- a/zh-cn/application-dev/quick-start/module-configuration-file.md +++ b/zh-cn/application-dev/quick-start/module-configuration-file.md @@ -486,7 +486,8 @@ extensionAbilities示例: > **说明:** > -> 在requestPermissions标签中配置的权限项将在应用级别生效,即该权限适用于整个应用程序。 +> - 在requestPermissions标签中配置的权限项将在应用级别生效,即该权限适用于整个应用程序。 +> - 如果应用需要订阅自己发布的事件,而且应用在extensionAbilities标签中的permissions字段中设置了访问该应用所需要的权限,那么应用也需要在requestPermissions标签中注册相关权限才能收到该事件。 **表8** **requestPermissions标签说明** diff --git a/zh-cn/application-dev/quick-start/shared-guide.md b/zh-cn/application-dev/quick-start/shared-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..a90453ac7072e643d78e8f98c229ce0c0848e17f --- /dev/null +++ b/zh-cn/application-dev/quick-start/shared-guide.md @@ -0,0 +1,19 @@ +# 共享包概述 + +OpenHarmony提供了两种共享包,[HAR(Harmony Achive)](har-package.md)静态共享包,和HSP(Harmony Shared Package)动态共享包。 + +HAR与HSP都是为了实现代码和资源的共享,都可以包含代码、C++库、资源和配置文件,最大的不同之处在于:HAR中的代码和资源跟随使用方编译,如果有多个使用方,它们的编译产物中会存在多份相同拷贝;而HSP中的代码和资源可以独立编译,运行时在一个进程中代码也只会存在一份。 + +**图1** `HAR`和`HSP`在`APP`包中的形态示意图 +![in-app-hsp-har](figures/in-app-hsp-har.png) + +**HSP旨在解决HAR存在的几个问题:** +- 多个`HAP`引用相同的`HAR`,导致的`APP`包大小膨胀问题。 +- 多个`HAP`引用相同的`HAR`,`HAR`中的一些状态变量无法共享的问题。 + +**HSP的一些约束:** +- `HSP`及其使用方都必须是`Stage`模型。 +- `HSP`及其使用方都必须使用`esmodule`编译模式。 +- `HSP`不支持在配置文件中声明`abilities`、`extensionAbilities`标签。 + +`HSP`按照使用场景可以分为[应用内HSP](in-app-hsp.md)和[应用间HSP](cross-app-hsp.md)。它们在配置文件和使用方式等方面有所区别。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 0a40190293d8d5d88864b118c96be99eea6edde2..bb9b81a8b5a47350b5abeb40b1f43d41d506a586 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -1,4 +1,4 @@ -# 接口 +# 接口 - [开发说明](development-intro.md) @@ -125,7 +125,20 @@ - [@ohos.notification (Notification模块)(待停用)](js-apis-notification.md) - application - [EventHub](js-apis-inner-application-eventHub.md) - + - commonEvent + - [CommonEventData](js-apis-inner-commonEvent-commonEventData.md) + - [CommonEventPublishData](js-apis-inner-commonEvent-commonEventPublishData.md) + - [CommonEventSubscriber](js-apis-inner-commonEvent-commonEventSubscriber.md) + - [CommonEventSubscribeInfo](js-apis-inner-commonEvent-commonEventSubscribeInfo.md) + - notification + - [NotificationActionButton](js-apis-inner-notification-notificationActionButton.md) + - [NotificationCommonDef](js-apis-inner-notification-notificationCommonDef.md) + - [NotificationContent](js-apis-inner-notification-notificationContent.md) + - [NotificationFlags](js-apis-inner-notification-notificationFlags.md) + - [NotificationRequest](js-apis-inner-notification-notificationRequest.md) + - [NotificationSlot](js-apis-inner-notification-notificationSlot.md) + - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) + - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) - 包管理 - [@ohos.bundle.appControl (appControl模块)](js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager模块)](js-apis-bundleManager.md) @@ -159,6 +172,8 @@ - [@ohos.pluginComponent(PluginComponentManager)](js-apis-plugincomponent.md) - [@ohos.promptAction (弹窗)](js-apis-promptAction.md) - [@ohos.router (页面路由)](js-apis-router.md) + - [@ohos.measure (文本计算)](js-apis-measure.md) + - [@ohos.uiAppearance(用户界面外观)](js-apis-uiappearance.md) - 图形图像 - [@ohos.animation.windowAnimationManager (窗口动画管理)](js-apis-windowAnimationManager.md) @@ -185,7 +200,7 @@ - [@ohos.intl (国际化-Intl)](js-apis-intl.md) - [@ohos.resourceManager (资源管理)](js-apis-resource-manager.md) -- 资源调度 +- 后台任务 - [@ohos.distributedMissionManager (分布式任务管理)](js-apis-distributedMissionManager.md) - [@ohos.reminderAgentManager (后台代理提醒)](js-apis-reminderAgentManager.md) - [@ohos.resourceschedule.backgroundTaskManager (后台任务管理)](js-apis-resourceschedule-backgroundTaskManager.md) @@ -203,7 +218,6 @@ - [@ohos.security.huks (通用密钥库系统)](js-apis-huks.md) - [@ohos.userIAM.faceAuth (人脸认证)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md) - - [@system.cipher (加密算法)](js-apis-system-cipher.md) - security - [PermissionRequestResult](js-apis-permissionrequestresult.md) @@ -226,12 +240,12 @@ - [@ohos.file.fileExtensionInfo (公共文件访问与管理属性信息)](js-apis-fileExtensionInfo.md) - [@ohos.file.fs (文件管理)](js-apis-file-fs.md) - [@ohos.file.hash (文件哈希处理)](js-apis-file-hash.md) + - [@ohos.file.picker (选择器)](js-apis-file-picker.md) - [@ohos.file.securityLabel (数据标签)](js-apis-file-securityLabel.md) - [@ohos.file.statvfs (文件系统空间统计)](js-apis-file-statvfs.md) - [@ohos.file.storageStatistics (应用空间统计)](js-apis-file-storage-statistics.md) - [@ohos.file.volumeManager (卷管理)](js-apis-file-volumemanager.md) - [@ohos.filemanagement.userFileManager (用户数据管理)](js-apis-userFileManager.md) - - [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md) - 电话服务 - [@ohos.contact (联系人)](js-apis-contact.md) @@ -389,6 +403,7 @@ - [@ohos.fileio (文件管理)](js-apis-fileio.md) - [@ohos.geolocation (位置服务)](js-apis-geolocation.md) - [@ohos.hiAppEvent (应用打点)](js-apis-hiappevent.md) + - [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](js-apis-statfs.md) @@ -400,6 +415,7 @@ - [@system.battery (电量信息)](js-apis-system-battery.md) - [@system.bluetooth (蓝牙)](js-apis-system-bluetooth.md) - [@system.brightness (屏幕亮度)](js-apis-system-brightness.md) + - [@system.cipher (加密算法)](js-apis-system-cipher.md) - [@system.configuration (应用配置)](js-apis-system-configuration.md) - [@system.device (设备信息)](js-apis-system-device.md) - [@system.fetch (数据请求)](js-apis-system-fetch.md) diff --git a/zh-cn/application-dev/reference/apis/commonEvent-definitions.md b/zh-cn/application-dev/reference/apis/commonEvent-definitions.md index 6de84fd8a843d2506b05d6df87dfc242d4c3190c..576f230600fe6d6d3e0c9809195009b436a31171 100644 --- a/zh-cn/application-dev/reference/apis/commonEvent-definitions.md +++ b/zh-cn/application-dev/reference/apis/commonEvent-definitions.md @@ -903,3 +903,7 @@ - 值:usual.event.QUICK_FIX_APPLY_RESULT - 订阅者所需权限:无 +## COMMON_EVENT_USER_INFO_UPDATED9+ +表示用户信息已更新。 +- 值:usual.event.USER_INFO_UPDATED +- 订阅者所需权限:无 diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md index 9fbf316d05afb22bf7870b8b9dcb2e073e0fc59f..997bf8437e729f08a341ec41029e61c0e06899d3 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md @@ -157,7 +157,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { > 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 -getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> +getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\\> 以异步方法获取指定用户所有的BundleInfo,使用Promise形式异步回调, @@ -201,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) > 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 -getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\\>): void 以异步方法获取当前用户所有的BundleInfo,使用callback形式返回结果。 @@ -238,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { > 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 -getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\\>): void 以异步方法获取系统中指定用户下所有的BundleInfo,使用callback形式返回结果。 @@ -823,7 +823,7 @@ bundle.getPermissionDef(permissionName).then((data) => { > 从API version 9开始不再维护,建议使用[bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo)替代。 -getAllApplicationInfo(bundleFlags: number, userId?: number): Promise> +getAllApplicationInfo(bundleFlags: number, userId?: number): Promise\\> 获取指定用户下所有已安装的应用信息,使用promise异步回调。 @@ -865,7 +865,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) > 从API version 9开始不再维护,建议使用[bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo)替代。 -getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void +getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback\\>): void 获取指定用户下所有已安装的应用信息,使用callback异步回调。 @@ -1320,7 +1320,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { > 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 -queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> +queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise\\> 以异步方法根据给定的意图获取Ability组件信息,使用Promise形式返回结果。 @@ -1371,7 +1371,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) > 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 -queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void +queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\\>): void 以异步方法根据给定的意图获取指定用户下Ability信息,使用callback形式返回结果。 @@ -1416,7 +1416,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { > 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 -queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; +queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback\\>): void; 以异步方法根据给定的意图获取Ability信息,使用callback形式返回结果。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md b/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md index 4fd64c90d6b8a6b86af701e9fc3d093ab011ca76..606805cd391f69e7eb471522a05626c3f746b7e7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -46,13 +46,6 @@ want操作的常数。用于表示要执行的通用操作。 | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | 指示选择文件的操作。 | | PARAMS_STREAM7+ | ability.params.stream | 指示发送数据时与目标关联的数据流的URI。对应的value必须是string类型的数组。 | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | 指示提供oauth服务的操作。 | -| ACTION_APP_ACCOUNT_AUTH 9+ | account.appAccount.action.auth | 指示提供auth服务的操作。 | -| ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | 表示从应用程序市场下载应用程序的的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| ACTION_MARKET_CROWDTEST 9+ | ohos.want.action.marketCrowdTest | 指示从应用程序市场众测应用程序的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_SANDBOX9+ |ohos.dlp.params.sandbox | 指示沙盒标志的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_BUNDLE_NAME9+ |ohos.dlp.params.bundleName |指示DLP Bundle名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_MODULE_NAME9+ |ohos.dlp.params.moduleName |指示DLP模块名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_ABILITY_NAME9+ |ohos.dlp.params.abilityName |指示DLP能力名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | | DLP_PARAMS_INDEX9+ |ohos.dlp.params.index |指示DLP索引参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | ## wantConstant.Entity @@ -91,6 +84,6 @@ Flags说明。用于表示处理Want的方式。 | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给 **[ohos.app.Context](js-apis-ability-context.md)** 中**startAbility**方法的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给 **FeatureAbility** 中[startAbility](js-apis-ability-featureAbility.md#startability)方法的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | | FLAG_ABILITY_NEW_MISSION | 0x10000000 | 指示在历史任务堆栈上创建任务的操作。 | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | 指示如果启动能力的现有实例已位于任务堆栈的顶部,则将重用该实例。否则,将创建一个新的能力实例。 | \ No newline at end of file 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 9d5752add2c1eef78d49b861fd2d151879e4506e..65f7d28de041725febfd25cdac582e4b268476fb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -63,7 +63,7 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | **示例:** @@ -110,7 +110,7 @@ verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | **示例:** @@ -139,7 +139,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被授予的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | -| permissionFlags | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | +| permissionFlags | number | 是 | 授权选项
- 0表示权限未经过用户主动设置。
- 1表示当次用户若选择禁止该权限,下次权限弹窗仍可以弹出申请用户授权。
- 2表示当次用户若选择禁止该权限,下次不会再弹出权限弹窗,需要用户在setting的权限管理中进行授权。
- 4表示当次权限设置为系统授权,用户不可更改这个权限授权状态。 | **返回值:** @@ -153,7 +153,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -196,7 +196,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。| | permissionName | Permissions | 是 | 被授予的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | -| permissionFlags | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | +| permissionFlags | number | 是 | 授权选项
- 0表示权限未经过用户主动设置。
- 1表示当次用户若选择禁止该权限,下次权限弹窗仍可以弹出申请用户授权。
- 2表示当次用户若选择禁止该权限,下次不会再弹出权限弹窗,需要用户在setting的权限管理中进行授权。
- 4表示当次权限设置为系统授权,用户不可更改这个权限授权状态。 | | callback | AsyncCallback<void> | 是 | 授予应用user grant权限。当授予权限成功时,err为undefine;否则为错误对象。 | **错误码:** @@ -205,7 +205,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -250,7 +250,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | -| permissionFlags | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | +| permissionFlags | number | 是 | 授权选项
- 0表示权限未经过用户主动设置。
- 1表示当次用户若选择禁止该权限,下次权限弹窗仍可以弹出申请用户授权。
- 2表示当次用户若选择禁止该权限,下次不会再弹出权限弹窗,需要用户在setting的权限管理中进行授权。
- 4表示当次权限设置为系统授权,用户不可更改这个权限授权状态。 | **返回值:** @@ -264,7 +264,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -307,7 +307,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | -| permissionFlags | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | +| permissionFlags | number | 是 | 授权选项
- 0表示权限未经过用户主动设置。
- 1表示当次用户若选择禁止该权限,下次权限弹窗仍可以弹出申请用户授权。
- 2表示当次用户若选择禁止该权限,下次不会再弹出权限弹窗,需要用户在setting的权限管理中进行授权。
- 4表示当次权限设置为系统授权,用户不可更改这个权限授权状态。 | | callback | AsyncCallback<void> | 是 | 撤销应用user grant权限。当撤销权限成功时,err为undefine;否则为错误对象。 | **错误码:** @@ -316,7 +316,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the flags value is invalid. | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -374,7 +374,7 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | @@ -451,7 +451,7 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionLi | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100004 | The interface is called repeatedly with the same input. | | 12100005 | The registration time has exceeded the limitation. | | 12100007 | Service is abnormal. | @@ -461,6 +461,7 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionLi ```js import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import bundle from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); @@ -502,7 +503,7 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionL | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID in list is all invalid. | +| 12100001 | The parameter is invalid. The tokenID in list is all invalid, or the permissionName in list is all invalid. | | 12100004 | The interface is not used together with "on". | | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | @@ -511,6 +512,7 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionL ```js import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import bundle from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); @@ -529,7 +531,9 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran 校验应用是否授予权限。使用Promise异步回调。 -> **说明:** 建议使用[checkAccessToken](#checkaccesstoken9)替代。 +> **说明:** +> +> 建议使用[checkAccessToken](#checkaccesstoken9)替代。 **系统能力:** SystemCapability.Security.AccessToken @@ -580,9 +584,10 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **错误码:** 以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 + | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | Parameter invalid. | +| 12100001 | The parameter is invalid. The context is invalid when it does not belong to the application itself. | **示例:** @@ -626,9 +631,10 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **错误码:** 以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 + | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | Parameter invalid. | +| 12100001 | The parameter is invalid. The context is invalid when it does not belong to the application itself. | **示例:** @@ -654,7 +660,9 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat 校验应用是否授予权限。使用Promise异步回调。 -> **说明:** 从API version 9开始不再维护,建议使用[checkAccessToken](#checkaccesstoken9)替代。 +> **说明:** +> +> 从API version 9开始不再维护,建议使用[checkAccessToken](#checkaccesstoken9)替代。 **系统能力:** SystemCapability.Security.AccessToken diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 1e6f6186b73b04d41e4cad2fc1eafe679f1d7f3b..d34d7553e15a5f606ccd3c5a7debb8f59a968b71 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -99,7 +99,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onContinue(wantParam) { - return AbilityConstant.OnConinueResult.AGREE; + return AbilityConstant.OnContinueResult.AGREE; } } ``` @@ -132,7 +132,7 @@ let option = { }; // 确保从上下文获取到context -this.context.startAbility(want, option).then(()={ +this.context.startAbility(want, option).then(()=>{ console.log('Succeed to start ability.'); }).catch((error)=>{ console.error('Failed to start ability with error: ${JSON.stringify(error)}'); diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index cb65694c20c8a95a2aae65493761943af5f972ee..cda0e7434c169a4e2dfdba1c06f21ca8cc6a59f8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -275,7 +275,7 @@ export default class MyFirstAbility extends UIAbility { // 2.通过applicationContext注册监听应用内生命周期 try { globalThis.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); - console.log('registerAbilityLifecycleCallback number: ${JSON.stringify(lifecycleId)}'); + console.log('registerAbilityLifecycleCallback lifecycleId: ${globalThis.lifecycleId}'); } catch (paramError) { console.error('error: ${paramError.code}, ${paramError.message}'); } @@ -285,7 +285,7 @@ export default class MyFirstAbility extends UIAbility { MySecondAbility.ts ```ts -import UIAbility from 'ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; export default class MySecondAbility extends UIAbility { onDestroy() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index 621aba9431df6a4b3808207ad83d21f75684e43d..0a51605b8cba3b3501ab5ee6b2f517be6f5b94bc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -59,12 +59,13 @@ updateConfiguration(config: Configuration, callback: AsyncCallback\): void ```ts import abilityManager from '@ohos.app.ability.abilityManager'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; const config = { language: 'Zh-Hans', // 简体中文 - colorMode: COLOR_MODE_LIGHT, // 浅色模式 - direction: DIRECTION_VERTICAL, // 垂直方向 - screenDensity: SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi' + colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT, // 浅色模式 + direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL, // 垂直方向 + screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi' displayId: 1, // 应用在Id为1的物理屏上显示 hasPointerDevice: true, // 指针类型设备已连接 }; @@ -116,12 +117,13 @@ updateConfiguration(config: Configuration): Promise\ ```ts import abilityManager from '@ohos.app.ability.abilityManager'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; const config = { language: 'Zh-Hans', // 简体中文 - colorMode: COLOR_MODE_LIGHT, // 浅色模式 - direction: DIRECTION_VERTICAL, // 垂直方向 - screenDensity: SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi' + colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT, // 浅色模式 + direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL, // 垂直方向 + screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi' displayId: 1, // 应用在Id为1的物理屏上显示 hasPointerDevice: true, // 指针类型设备已连接 }; diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md index e21fa06af545b8620f13fc7a2b3a45de3570b229..61bac516c4a4fd99131fbc1c7c271e922d082f0e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -459,7 +459,7 @@ off(type: 'applicationState', observerId: number, callback: AsyncCallback\; ```ts import appManager from '@ohos.app.ability.appManager'; -let observeId = 0; +let observerId = 0; // 1.注册应用状态监听器 let applicationStateObserver = { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index 50a0c9579711d987b6a02070d7407eced15925f2..8658417d06f5e70a9f87a3ae9555a6fa82a628fa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -4,7 +4,7 @@ appRecovery模块提供了应用在故障状态下的恢复能力。 > **说明:** > -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。当前版本仅支持单进程中单Ability的应用恢复。 +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。API9仅支持单进程中单Ability的应用恢复。API10支持进程中包含多个Ability的场景。 ## 导入模块 ```ts @@ -51,7 +51,7 @@ import appRecovery from '@ohos.app.ability.appRecovery'; enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; -使能应用恢复功能,参数按顺序填入。 +使能应用恢复功能,参数按顺序填入。该接口调用后,应用从启动器启动时第一个Ability支持恢复。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -72,9 +72,9 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { onCreate() { appRecovery.enableAppRecovery( - appRecovery.RestartFlag::ALWAYS_RESTART, - appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR, - appRecovery.SaveModeFlag::SAVE_WITH_FILE + appRecovery.RestartFlag.ALWAYS_RESTART, + appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR, + appRecovery.SaveModeFlag.SAVE_WITH_FILE ); } } @@ -84,7 +84,14 @@ export default class MyAbilityStage extends AbilityStage { restartApp(): void; -重启当前App进程,可以配合[errorManager](js-apis-app-ability-errorManager.md)相关接口使用。 +重启当前进程,并拉起应用启动时第一个Ability,如果该Ability存在已经保存的状态,这些状态数据会在Ability的OnCreate生命周期回调的want参数中作为wantParam属性传入。 + +API10时将启动由[setRestartWant](#apprecoverysetrestartwant)指定的Ability。如果没有指定则按以下规则启动:\ +如果当前应用前台的Ability支持恢复,则重新拉起该Ability。\ +如果存在多个支持恢复的Ability处于前台,则只拉起最后一个。\ +如果没有Ability处于前台,则不拉起。 + +可以配合[errorManager](js-apis-app-ability-errorManager.md)相关接口使用。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -142,3 +149,53 @@ try { console.error('error: ${paramError.code}, ${paramError.message}'); } ``` + +## appRecovery.saveAppState10+ + +saveAppState(context?: UIAbilityContext): boolean; + +主动保存Ability的状态,这个状态将在下次恢复启动时使用。可以配合[errorManager](js-apis-app-ability-errorManager.md)相关接口使用 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 保存成功与否。true:保存成功,false:保存失败。 | + +**示例:** + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +onBackground() { + hilog.info(0x0000, '[demo]', '%{public}s', 'EntryAbility onBackground'); + appRecovery.saveAppState(this.context) +} +``` + +## appRecovery.setRestartWant10+ + +setRestartWant(want: Want): void; + +设置下次恢复主动拉起场景下的Ability。该Ability必须为当前包下的UIAbility。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**示例:** + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +Button("启动到恢复Ability") + .fontSize(40) + .fontWeight(FontWeight.Bold) + .onClick(()=> { + // set restart want + let want = { + bundleName: "ohos.samples.recovery", + abilityName: "RecoveryAbility" + }; + + appRecovery.setRestartWant(want); + }) +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index cddd09e717948af700578b2b80bdbdf94c58c26b..d81a587c78a62aa5d413cf9ab10860cabc5c6beb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -35,7 +35,7 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; 注册系统环境变化的监听后,在系统内存变化时触发回调。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **参数:** @@ -55,7 +55,7 @@ export default class MyAbility extends UIAbility { onCreate() { console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); - let EnvironmentCallback = { + let environmentCallback = { onConfigurationUpdated(config){ console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); } @@ -67,7 +67,7 @@ export default class MyAbility extends UIAbility { // 1.获取applicationContext let applicationContext = globalThis.applicationContext; // 2.通过applicationContext注册监听应用内生命周期 - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + callbackId = applicationContext.registerEnvironmentCallback(environmentCallback); console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}'); } onDestroy() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 97cc759d203d74b68ddd0c59de0da47e255833f3..13170311701300302241b40d1e4f934e8feb6b20 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -290,7 +290,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M | -------- | -------- | -------- | -------- | | deviceId | string | 是 | 设备ID,本机默认为空字符串。 | | missionId | number | 是 | 任务ID。 | - | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md))> | 是 | 执行结果回调函数,返回任务信息。 | + | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md)> | 是 | 执行结果回调函数,返回任务信息。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 0b27ca5b66f7157df5a301df10f07150968f9173..bc17ac5a0e514bfc1526eb5771399029faae9a24 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -106,7 +106,7 @@ Extension生命周期回调,如果是startAbility或者startServiceExtensionAb ## ServiceExtensionAbility.onConnect -onConnect(want: Want): rpc.RemoteObject; +onConnect(want: Want): rpc.RemoteObject | Promise; Extension生命周期回调,如果是connectAbility拉起的服务,会在onCreate之后回调。返回一个RemoteObject对象,用于客户端和服务端进行通信。 @@ -148,7 +148,7 @@ Extension生命周期回调,如果是connectAbility拉起的服务,会在onC ## ServiceExtensionAbility.onDisconnect -onDisconnect(want: Want): void; +onDisconnect(want: Want): void | Promise; Extension的生命周期回调,客户端执行断开连接服务时回调。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 070de1799439d2f830309b00bd804f249b4b8db5..dcdd97f4ab4e4b2b0d58d73c491e651309e7ce34 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -124,7 +124,7 @@ onWindowStageRestore(windowStage: window.WindowStage): void ## UIAbility.onDestroy -onDestroy(): void; +onDestroy(): void | Promise<void>; UIAbility生命周期回调,在销毁时回调,执行资源清理等操作。 @@ -181,7 +181,7 @@ UIAbility生命周期回调,当应用从前台转到后台时触发。 ## UIAbility.onContinue -onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; +onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResult; 当ability迁移准备迁移时触发,保存数据。 @@ -267,7 +267,7 @@ onDump(params: Array\): Array\; ## UIAbility.onSaveState -onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; +onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult; 该API配合[appRecovery](js-apis-app-ability-appRecovery.md)使用。在应用故障时,如果使能了自动保存状态,框架将回调onSaveState保存UIAbility状态。 @@ -308,7 +308,7 @@ class MyUIAbility extends UIAbility { ## Caller.call -call(method: string, data: rpc.Sequenceable): Promise<void>; +call(method: string, data: rpc.Parcelable): Promise<void>; 向通用组件服务端发送约定序列化数据。 @@ -319,7 +319,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | method | string | 是 | 约定的服务端注册事件字符串。 | -| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | 是 | 由开发者实现的Sequenceable可序列化数据。 | +| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | 是 | 由开发者实现的Parcelable可序列化数据。 | **返回值:** @@ -338,7 +338,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; **示例:** ```ts - class MyMessageAble{ // 自定义的Sequenceable数据结构 + class MyMessageAble{ // 自定义的Parcelable数据结构 name:'' str:'' num: 1 @@ -346,15 +346,15 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } @@ -369,7 +369,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; deviceId: '' }).then((obj) => { caller = obj; - let msg = new MyMessageAble('msg', 'world'); // 参考Sequenceable数据定义 + let msg = new MyMessageAble('msg', 'world'); // 参考Parcelable数据定义 caller.call(method, msg) .then(() => { console.log('Caller call() called'); @@ -387,7 +387,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; ## Caller.callWithResult -callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; +callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence>; 向通用组件服务端发送约定序列化数据, 并将服务端返回的约定序列化数据带回。 @@ -398,13 +398,13 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | method | string | 是 | 约定的服务端注册事件字符串。 | -| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | 是 | 由开发者实现的Sequenceable可序列化数据。 | +| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | 是 | 由开发者实现的Parcelable可序列化数据。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Promise<[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)> | Promise形式返回通用组件服务端应答数据。 | +| Promise<[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)> | Promise形式返回通用组件服务端应答数据。 | **错误码:** @@ -425,15 +425,15 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]'); return true; } @@ -453,7 +453,7 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa .then((data) => { console.log('Caller callWithResult() called'); let retmsg = new MyMessageAble(0, ''); - data.readSequenceable(retmsg); + data.readParcelable(retmsg); }) .catch((callErr) => { console.log('Caller.callWithResult catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}'); @@ -509,7 +509,7 @@ release(): void; ## Caller.onRelease - onRelease(callback: OnReleaseCallBack): void; + onRelease(callback: OnReleaseCallback): void; 注册通用组件服务端Stub(桩)断开监听通知。 @@ -519,7 +519,7 @@ release(): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | [OnReleaseCallBack](#onreleasecallback) | 是 | 返回onRelease回调结果。 | +| callback | [OnReleaseCallback](#onreleasecallback) | 是 | 返回onRelease回调结果。 | **示例:** @@ -560,7 +560,7 @@ release(): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 监听releaseCall事件,固定为'release'。 | -| callback | [OnReleaseCallBack](#onreleasecallback) | 是 | 返回onRelease回调结果。 | +| callback | [OnReleaseCallback](#onreleasecallback) | 是 | 返回onRelease回调结果。 | **错误码:** @@ -609,7 +609,7 @@ off(type: 'release', callback: OnReleaseCallback): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 监听releaseCall事件,固定为'release'。 | -| callback | [OnReleaseCallBack](#onreleasecallback) | 是 | 返回off回调结果。 | +| callback | [OnReleaseCallback](#onreleasecallback) | 是 | 返回off回调结果。 | **错误码:** @@ -712,7 +712,7 @@ on(method: string, callback: CalleeCallback): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | method | string | 是 | 与客户端约定的通知消息字符串。 | -| callback | [CalleeCallback](#calleecallback) | 是 | 一个[rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)类型入参的js通知同步回调函数, 回调函数至少要返回一个空的[rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated)数据对象, 其他视为函数执行错误。 | +| callback | [CalleeCallback](#calleecallback) | 是 | 一个[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)类型入参的js通知同步回调函数, 回调函数至少要返回一个空的[rpc.Parcelable](js-apis-rpc.md#parcelable9)数据对象, 其他视为函数执行错误。 | **错误码:** @@ -733,15 +733,15 @@ on(method: string, callback: CalleeCallback): void; this.name = name; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } @@ -750,7 +750,7 @@ on(method: string, callback: CalleeCallback): void; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ${pdata}'); let msg = new MyMessageAble('test', ''); - pdata.readSequenceable(msg); + pdata.readParcelable(msg); return new MyMessageAble('test1', 'Callee test'); } export default class MainUIAbility extends UIAbility { @@ -816,10 +816,10 @@ off(method: string): void; ## CalleeCallback -(indata: rpc.MessageParcel): rpc.Sequenceable; +(indata: rpc.MessageSequence): rpc.Parcelable; **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore | 名称 | 可读 | 可写 | 类型 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | 是 | 否 | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | 被调用方注册的消息侦听器函数接口的原型。 | +| (indata: [rpc.MessageSequence](js-apis-rpc.md#messagesequence9)) | 是 | 否 | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | 被调用方注册的消息侦听器函数接口的原型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index 5b3007d03598baf856db06c86a9a675efe2e8567..18c63edc927aacb86d53917e94eeb63b84f2cd2b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -273,7 +273,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ## onShareForm -onShareForm?(formId: string): { [key: string]: any } +onShareForm?(formId: string): { [key: string]: Object } 卡片提供方接收卡片分享的通知接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index bb37534a86ff2831456083701d8fd21d39e1389a..d83bfe08bb64c405f5ed4e5b3de2bde89c1a4399 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -42,22 +42,22 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens | 名称 | 描述 | | ------------- | ------------ | -| left | 表示向左的手势。 | -| leftThenRight | 表示先向左再向右的手势。 | -| leftThenUp | 表示先向左再向上的手势。 | -| leftThenDown | 表示先向左再向下的手势。 | -| right | 表示向右的手势。 | -| rightThenLeft | 表示先向右再向左的手势。 | -| rightThenUp | 表示先向右再向上的手势。 | -| rightThenDown | 表示先向右再向下的手势。 | -| up | 表示向上的手势。 | -| upThenLeft | 表示先向上再向左的手势。 | -| upThenRight | 表示先向上再向右的手势。 | -| upThenDown | 表示先向上再向下的手势。 | -| down | 表示向下的手势。 | -| downThenLeft | 表示先向下再向左的手势。 | -| downThenRight | 表示先向下再向右的手势。 | -| downThenUp | 表示先向下再向上的手势。 | +| left | 类型为字符串,表示向左的手势。 | +| leftThenRight | 类型为字符串,表示先向左再向右的手势。 | +| leftThenUp | 类型为字符串,表示先向左再向上的手势。 | +| leftThenDown | 类型为字符串,表示先向左再向下的手势。 | +| right | 类型为字符串,表示向右的手势。 | +| rightThenLeft | 类型为字符串,表示先向右再向左的手势。 | +| rightThenUp | 类型为字符串,表示先向右再向上的手势。 | +| rightThenDown | 类型为字符串,表示先向右再向下的手势。 | +| up | 类型为字符串,表示向上的手势。 | +| upThenLeft | 类型为字符串,表示先向上再向左的手势。 | +| upThenRight | 类型为字符串,表示先向上再向右的手势。 | +| upThenDown | 类型为字符串,表示先向上再向下的手势。 | +| down | 类型为字符串,表示向下的手势。 | +| downThenLeft | 类型为字符串,表示先向下再向左的手势。 | +| downThenRight | 类型为字符串,表示先向下再向右的手势。 | +| downThenUp | 类型为字符串,表示先向下再向上的手势。 | ## PageUpdateType @@ -67,8 +67,8 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens | 名称 | 描述 | | ----------------- | --------- | -| pageContentUpdate | 表示页面内容刷新。 | -| pageStateUpdate | 表示页面状态刷新。 | +| pageContentUpdate | 类型为字符串,表示页面内容刷新。 | +| pageStateUpdate | 类型为字符串,表示页面状态刷新。 | ## TouchGuideType @@ -78,8 +78,8 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens | 名称 | 描述 | | ---------- | ------------ | -| touchBegin | 表示触摸浏览时开始触摸。 | -| touchEnd | 表示触摸浏览时结束触摸。 | +| touchBegin | 类型为字符串,表示触摸浏览时开始触摸。 | +| touchEnd | 类型为字符串,表示触摸浏览时结束触摸。 | ## AccessibilityExtensionAbility.onConnect diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md index a8c1a093346c766f49cab9c0fd6263a4dba55dc4..9d6cd83ab9a2d955d6ac92cfa7df21a3b4281df8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md @@ -263,49 +263,6 @@ registerApplicationStateObserver(observer: ApplicationStateObserver): number; console.log('-------- observerCode: ---------', observerCode); ``` -## appManager.registerApplicationStateObserver9+ - -registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; - -注册指定应用程序状态观测器。 - -**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**:该接口为系统接口,三方应用不支持调用。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | 是 | 返回观察者的数字代码。 | -| bundleNameList | Array | 是 | 表示需要注册监听的bundleName数组。最大值128。 | - -**示例:** - - ```ts - let applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - }; - let bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - ``` ## appManager.unregisterApplicationStateObserver8+ unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md index 4a8ad3cb8d203b5b62fa5f3911bb42b855d52b48..b9b86a80fa48dbe3e8b21b4b752a3f0eb97ccd5f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @@ -33,11 +33,14 @@ export default class EntryAbility extends UIAbility { console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; + }, + onMemoryLevel(level){ + console.log('onMemoryLevel level: ${JSON.stringify(level)}'); } }; let applicationContext = this.context.getApplicationContext(); - applicationContext.registerEnvironmentCallback(envCallback); + applicationContext.on('environment',envCallback); windowStage.loadContent('pages/index', (err, data) => { if (err.code) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md index 7ec7acabd0f63624a2175226160689c74162426f..6338badb4810ea184689de12d0278260db64c76f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md @@ -382,97 +382,6 @@ getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnaps }); ``` -## missionManager.getLowResolutionMissionSnapShot9+ - -getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; - -获取任务低分辨率快照。 - -**需要权限**:ohos.permission.MANAGE_MISSIONS - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | deviceId | string | 是 | 设备ID,本机默认为空字符串。 | - | missionId | number | 是 | 任务ID。 | - | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | 是 | 执行结果回调函数,返回任务快照信息。 | - -**示例:** - - ```ts - import missionManager from '@ohos.application.missionManager'; - - missionManager.getMissionInfos('', 10, (error, missions) => { - if (error.code) { - console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); - return; - } - console.log('size = ${missions.length}'); - console.log('missions = ${JSON.stringify(missions)}'); - let id = missions[0].missionId; - - missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => { - if (error.code) { - console.error('getLowResolutionMissionSnapShot failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); - return; - } - console.log('bundleName = ${snapshot.ability.bundleName}'); - }); - }); - ``` - - -## missionManager.getLowResolutionMissionSnapShot9+ - -getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; - -获取任务低分辨率快照。 - -**需要权限**:ohos.permission.MANAGE_MISSIONS - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | deviceId | string | 是 | 设备ID,本机默认为空字符串。 | - | missionId | number | 是 | 任务ID。 | - -**返回值:** - - | 类型 | 说明 | - | -------- | -------- | - | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | 任务快照信息。 | - -**示例:** - - ```ts - import missionManager from '@ohos.application.missionManager'; - - let allMissions; - missionManager.getMissionInfos('',10).then(function(res){ - allMissions=res; - }).catch(function(error) { - console.error('getMissionInfos fail, error: ${error}'); - }); - console.log('size = ${allMissions.length}'); - console.log('missions = ${JSON.stringify(allMissions)}'); - let id = allMissions[0].missionId; - - let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (error){ - console.error('getLowResolutionMissionSnapShot fail, error: ${error}'); - }); - ``` - - ## missionManager.lockMission lockMission(missionId: number, callback: AsyncCallback<void>): void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-want.md b/zh-cn/application-dev/reference/apis/js-apis-application-want.md index c8c632e9b60a90f31bc8b99b19cd2e0aaa05642e..f7d00402995f666cd8eb47062b2c61b789fdc285 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-want.md @@ -27,7 +27,6 @@ import Want from '@ohos.application.Want'; | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md)。 | | parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | | entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 | -| moduleName9+ | string | 否 | 表示待启动的Ability所属的模块(module)。 | **示例:** 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 6f465e2fdf0399169ef4547d49f75614838b56ba..11ba2ba08458236b144c32c3f7111e351d4035b9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -4539,15 +4539,15 @@ let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let stat = await fs.stat(path); let buf = new ArrayBuffer(bufferSize); -let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); +let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); for (let i = 0;i < len; i++) { let options = { - offset: i * this.bufferSize, - length: this.bufferSize + offset: i * bufferSize, + length: bufferSize } let readsize = await fs.read(file.fd, buf, options) let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer.write(buf,(err,writeSize)=>{ + audioRenderer.write(buf,(err,writeSize)=>{ if(err){ reject(err) }else{ @@ -4593,15 +4593,15 @@ let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let stat = await fs.stat(path); let buf = new ArrayBuffer(bufferSize); -let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); +let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); for (let i = 0;i < len; i++) { let options = { - offset: i * this.bufferSize, - length: this.bufferSize + offset: i * bufferSize, + length: bufferSize } let readsize = await fs.read(file.fd, buf, options) try{ - let writeSize = await this.audioRenderer.write(buf); + let writeSize = await audioRenderer.write(buf); } catch(err) { console.error(`audioRenderer.write err: ${err}`); } @@ -5424,7 +5424,7 @@ release(callback: AsyncCallback): void | 参数名 | 类型 | 必填 | 说明 | | :------- | :------------------- | :--- | :---------------------------------- | -| callback | AsyncCallback | 是 | Callback used to return the result. | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-avsession.md b/zh-cn/application-dev/reference/apis/js-apis-avsession.md index 552b10b89e557e4c0152281a125f38c062638310..92a3d81ebaad1d37ace61f40bd596bd35a9da2b0 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-avsession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-avsession.md @@ -26,6 +26,8 @@ createAVSession(context: Context, tag: string, type: AVSessionType): Promise\ | 是 | 回调函数。回调返回会话实例对象,可用于获取会话ID,以及设置元数据、播放状态,发送按键事件等操作。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -128,7 +132,7 @@ getAllSessionDescriptors(): Promise\>> | Promise\\>\> | Promise对象。返回所有会话描述的只读对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -155,7 +159,7 @@ getAllSessionDescriptors(callback: AsyncCallback\\>\> | 是 | 回调函数。返回所有会话描述的只读对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -191,6 +195,99 @@ avSession.getAllSessionDescriptors(function (err, descriptors) { }); ``` +## avSession.getHistoricalSessionDescriptors10+ + +getHistoricalSessionDescriptors(maxSize?: number): Promise\>> + +获取所有会话的相关描述。结果通过Promise异步回调方式返回。 + +**需要权限:** ohos.permission.MANAGE_MEDIA_RESOURCES + +**系统能力:** SystemCapability.Multimedia.AVSession.Manager + +**系统接口:** 该接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -----------------------------------------------------------------| +| maxSize | number | 否 | 指定获取描述符数量的最大值,可选范围是0-10,不填则取默认值,默认值为3。| + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------------------------------------------- | -------------------------------------- | +| Promise\\>\> | Promise对象。返回所有会话描述的只读对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | + +**示例:** + +```js +avSession.getHistoricalSessionDescriptors().then((descriptors) => { + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); + if(descriptors.length > 0 ){ + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); + } +}).catch((err) => { + console.info(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +## avSession.getHistoricalSessionDescriptors10+ + +getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\>>): void + +获取所有会话的相关描述。结果通过callback异步回调方式返回。 + +**需要权限:** ohos.permission.MANAGE_MEDIA_RESOURCES。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Manager + +**系统接口:** 该接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------------------------ | ---- | -----------------------------------------------------------------| +| maxSize | number | 是 | 指定获取描述符数量的最大值,可选范围是0-10,不填则取默认值,默认值为3。| +| callback | AsyncCallback\>\> | 是 | 回调函数。返回所有会话描述的只读对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 |Session service exception. | + +**示例:** + +```js +avSession.getHistoricalSessionDescriptors(1, function (err, descriptors) { + if (err) { + console.info(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); + if(descriptors.length > 0 ){ + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); + } + } +}); +``` + ## avSession.createController createController(sessionId: string): Promise\ @@ -216,7 +313,7 @@ createController(sessionId: string): Promise\ | Promise<[AVSessionController](#avsessioncontroller)\> | Promise对象。返回会话控制器实例,可查看会话ID,
并完成对会话发送命令及事件,获取元数据、播放状态信息等操作。| **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -268,7 +365,7 @@ createController(sessionId: string, callback: AsyncCallback\ | 是 | 回调函数。返回会话控制器实例,可查看会话ID,
并完成对会话发送命令及事件,获取元数据、播放状态信息等操作。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -330,7 +427,7 @@ castAudio(session: SessionToken | 'all', audioDevices: Array | Promise对象。当投播成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -382,7 +479,7 @@ castAudio(session: SessionToken | 'all', audioDevices: Array | 是 | 回调函数。当投播成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -433,7 +530,7 @@ on(type: 'sessionCreate' | 'sessionDestroy' | 'topSessionChange', callback: (ses | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | 是 | 回调函数。参数为会话相关描述。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -481,7 +578,7 @@ off(type: 'sessionCreate' | 'sessionDestroy' | 'topSessionChange', callback?: (s | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为会话相关描述,为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -503,6 +600,8 @@ on(type: 'sessionServiceDie', callback: () => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -511,7 +610,7 @@ on(type: 'sessionServiceDie', callback: () => void): void | callback | callback: () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -533,6 +632,8 @@ off(type: 'sessionServiceDie', callback?: () => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -541,7 +642,7 @@ off(type: 'sessionServiceDie', callback?: () => void): void | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的服务死亡监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -578,7 +679,7 @@ sendSystemAVKeyEvent(event: KeyEvent): Promise\ | Promise | Promise对象。当事件发送成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -620,7 +721,7 @@ sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当事件发送成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -667,7 +768,7 @@ sendSystemControlCommand(command: AVControlCommand): Promise\ | Promise | Promise对象。当命令发送成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -721,7 +822,7 @@ sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -765,6 +866,8 @@ avSession.sendSystemControlCommand(avcommand, function (err) { **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 可读 | 可写 | 说明 | | :-------- | :----- | :--- | :--- | :---------------------------- | @@ -784,6 +887,8 @@ setAVMetadata(data: AVMetadata): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -797,7 +902,7 @@ setAVMetadata(data: AVMetadata): Promise\ | Promise | Promise对象。当元数据设置成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -838,6 +943,8 @@ setAVMetadata(data: AVMetadata, callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -846,7 +953,7 @@ setAVMetadata(data: AVMetadata, callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当元数据设置成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -889,6 +996,8 @@ setAVPlaybackState(state: AVPlaybackState): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -902,7 +1011,7 @@ setAVPlaybackState(state: AVPlaybackState): Promise\ | Promise | Promise对象。当播放状态设置成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -935,6 +1044,8 @@ setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -943,7 +1054,7 @@ setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当播放状态设置成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -970,6 +1081,216 @@ session.setAVPlaybackState(PlaybackState, function (err) { }); ``` +### setAVQueueItems10+ + +setAVQueueItems(items: Array\): Promise + +设置媒体播放列表。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ---------------------------------- | +| items | Array<[AVQueueItem](#avqueueitem10)\> | 是 | 播放列表单项的队列,用以表示播放列表。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise | Promise对象。当播放列表设置成功,无返回结果,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +let queueItemDescription_1 = { + mediaId: '001', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_1 = { + itemId: 1, + description: queueItemDescription_1 +}; +let queueItemDescription_2 = { + mediaId: '002', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_2 = { + itemId: 2, + description: queueItemDescription_2 +}; +let queueItemsArray = [queueItem_1, queueItem_2]; +session.setAVQueueItems(queueItemsArray).then(() => { + console.info('SetAVQueueItems successfully'); +}).catch((err) => { + console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### setAVQueueItems10+ + +setAVQueueItems(items: Array\, callback: AsyncCallback): void + +设置媒体播放列表。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ----------------------------------------------------------- | +| items | Array<[AVQueueItem](#avqueueitem10)\> | 是 | 播放列表单项的队列,用以表示播放列表。 | +| callback | AsyncCallback | 是 | 回调函数。当播放状态设置成功,err为undefined,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +let queueItemDescription_1 = { + mediaId: '001', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_1 = { + itemId: 1, + description: queueItemDescription_1 +}; +let queueItemDescription_2 = { + mediaId: '002', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.icon.uri.com', + extras: {'extras':'any'} +}; +let queueItem_2 = { + itemId: 2, + description: queueItemDescription_2 +}; +let queueItemsArray = [queueItem_1, queueItem_2]; +session.setAVQueueItems(queueItemsArray, function (err) { + if (err) { + console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SetAVQueueItems successfully'); + } +}); +``` + +### setAVQueueTitle10+ + +setAVQueueTitle(title: string): Promise\ + +设置媒体播放列表名称。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------- | +| title | string | 是 | 播放列表的名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise | Promise对象。当播放列表设置成功,无返回结果,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +let queueTitle = 'QUEUE_TITLE'; +session.setAVQueueTitle(queueTitle).then(() => { + console.info('SetAVQueueTitle successfully'); +}).catch((err) => { + console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### setAVQueueTitle10+ + +setAVQueueTitle(title: string, callback: AsyncCallback\): void + +设置媒体播放列表名称。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| title | string | 是 | 播放列表名称字段。 | +| callback | AsyncCallback | 是 | 回调函数。当播放状态设置成功,err为undefined,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +let queueTitle = 'QUEUE_TITLE'; +session.setAVQueueTitle(queueTitle, function (err) { + if (err) { + console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SetAVQueueTitle successfully'); + } +}); +``` + ### setLaunchAbility setLaunchAbility(ability: WantAgent): Promise\ @@ -978,6 +1299,8 @@ setLaunchAbility(ability: WantAgent): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -991,7 +1314,7 @@ setLaunchAbility(ability: WantAgent): Promise\ | Promise | Promise对象。当Ability设置成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1048,6 +1371,8 @@ setLaunchAbility(ability: WantAgent, callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1056,7 +1381,7 @@ setLaunchAbility(ability: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当Ability设置成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1107,9 +1432,9 @@ wantAgent.getWantAgent(wantAgentInfo).then((agent) => { }); ``` -### setSessionEvent10+ +### dispatchSessionEvent10+ -setSessionEvent(event: string, args: {[key: string]: any}): Promise\ +dispatchSessionEvent(event: string, args: {[key: string]: Object}): Promise\ 媒体提供方设置一个会话内自定义事件,包括事件名和键值对形式的事件内容, 结果通过Promise异步回调方式返回。 @@ -1131,7 +1456,7 @@ setSessionEvent(event: string, args: {[key: string]: any}): Promise\ | Promise | Promise对象。当事件设置成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1145,14 +1470,14 @@ let eventName = "dynamic_lyric"; let args = { lyric : "This is lyric" } -await session.setSessionEvent(eventName, args).catch((err) => { - console.info(`SetSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); +await session.dispatchSessionEvent(eventName, args).catch((err) => { + console.info(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); }) ``` -### setSessionEvent10+ +### dispatchSessionEvent10+ -setSessionEvent(event: string, args: {[key: string]: any}, callback: AsyncCallback): void +dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback): void 媒体提供方设置一个会话内自定义事件,包括事件名和键值对形式的事件内容, 结果通过callback异步回调方式返回。 @@ -1169,7 +1494,7 @@ setSessionEvent(event: string, args: {[key: string]: any}, callback: AsyncCallba | callback | AsyncCallback | 是 | 回调函数。当会话事件设置成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1183,9 +1508,9 @@ let eventName = "dynamic_lyric"; let args = { lyric : "This is lyric" } -await session.setSessionEvent(eventName, args, (err) => { +await session.dispatchSessionEvent(eventName, args, (err) => { if(err) { - console.info(`SetSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); + console.info(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`); } }) ``` @@ -1198,6 +1523,8 @@ getController(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -1205,7 +1532,7 @@ getController(): Promise\ | Promise<[AVSessionController](#avsessioncontroller)> | Promise对象。返回会话控制器。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1232,6 +1559,8 @@ getController(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1239,7 +1568,7 @@ getController(callback: AsyncCallback\): void | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | 是 | 回调函数。返回会话控制器。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1268,6 +1597,8 @@ getOutputDevice(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -1275,7 +1606,7 @@ getOutputDevice(): Promise\ | Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise对象。返回播放设备信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1300,6 +1631,8 @@ getOutputDevice(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1307,7 +1640,7 @@ getOutputDevice(callback: AsyncCallback\): void | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | 是 | 回调函数,返回播放设备信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1334,6 +1667,8 @@ activate(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -1341,7 +1676,7 @@ activate(): Promise\ | Promise | Promise对象。当会话激活成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1366,6 +1701,8 @@ activate(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1373,7 +1710,7 @@ activate(callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当会话激活成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1400,6 +1737,8 @@ deactivate(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -1407,7 +1746,7 @@ deactivate(): Promise\ | Promise | Promise对象。当禁用会话成功,无返回结果,否则返回错误对象。| **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1434,6 +1773,8 @@ deactivate(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1441,7 +1782,7 @@ deactivate(callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当禁用会话成功,err为undefined,否则返回错误对象。| **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1468,6 +1809,8 @@ destroy(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -1475,7 +1818,7 @@ destroy(): Promise\ | Promise | Promise对象。当会话销毁成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1498,9 +1841,10 @@ destroy(callback: AsyncCallback\): void 销毁当前会话,使当前会话完全失效。结果通过callback异步回调方式返回。 - **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1508,7 +1852,7 @@ destroy(callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当会话销毁成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1535,6 +1879,8 @@ on(type: 'play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind', **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1543,7 +1889,7 @@ on(type: 'play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind', | callback | callback: () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则为错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1584,6 +1930,8 @@ on(type: 'seek', callback: (time: number) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1592,7 +1940,7 @@ on(type: 'seek', callback: (time: number) => void): void | callback | (time: number) => void | 是 | 回调函数。参数time是时间节点,单位为毫秒。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1615,6 +1963,8 @@ on(type: 'setSpeed', callback: (speed: number) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1623,7 +1973,7 @@ on(type: 'setSpeed', callback: (speed: number) => void): void | callback | (speed: number) => void | 是 | 回调函数。参数speed是播放倍速。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1646,6 +1996,8 @@ on(type: 'setLoopMode', callback: (mode: LoopMode) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1654,7 +2006,7 @@ on(type: 'setLoopMode', callback: (mode: LoopMode) => void): void | callback | (mode: [LoopMode](#loopmode)) => void | 是 | 回调函数。参数mode是循环模式。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1677,6 +2029,8 @@ on(type: 'toggleFavorite', callback: (assetId: string) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1685,7 +2039,7 @@ on(type: 'toggleFavorite', callback: (assetId: string) => void): void | callback | (assetId: string) => void | 是 | 回调函数。参数assetId是媒体ID。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1700,23 +2054,25 @@ session.on('toggleFavorite', (assetId) => { }); ``` -### on('handleKeyEvent') +### on('skipToQueueItem')10+ -on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void +on(type: 'skipToQueueItem', callback: (itemId: number) => void): void -设置按键事件的监听 +设置播放列表其中某项被选中的监听事件,session端可以选择对这个单项歌曲进行播放。 **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'handleKeyEvent'`:当按键事件被发送到会话时,触发该事件。 | -| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | 是 | 回调函数。参数event是按键事件。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------------------------------------------------------------------------------- | +| type | string | 是 | 事件回调类型,支持事件`'skipToQueueItem'`:当播放列表选中单项的命令被发送到会话时,触发该事件。 | +| callback | (itemId: number) => void | 是 | 回调函数。参数itemId是选中的播放列表项的ID。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1726,28 +2082,63 @@ on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void **示例:** ```js -session.on('handleKeyEvent', (event) => { - console.info(`on handleKeyEvent event : ${event}`); +session.on('skipToQueueItem', (itemId) => { + console.info(`on skipToQueueItem id : ${itemId}`); }); ``` -### on('outputDeviceChange') +### on('handleKeyEvent') -on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): void +on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void -设置播放设备变化的监听事件。 +设置按键事件的监听 **系统能力:** SystemCapability.Multimedia.AVSession.Core -**参数:** +**系统接口:** 该接口为系统接口 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'outputDeviceChange'`:当播放设备变化时,触发该事件。 | -| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | 是 | 回调函数。参数device是设备相关信息。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持事件`'handleKeyEvent'`:当按键事件被发送到会话时,触发该事件。 | +| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | 是 | 回调函数。参数event是按键事件。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +session.on('handleKeyEvent', (event) => { + console.info(`on handleKeyEvent event : ${event}`); +}); +``` + +### on('outputDeviceChange') + +on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): void + +设置播放设备变化的监听事件。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持事件`'outputDeviceChange'`:当播放设备变化时,触发该事件。 | +| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | 是 | 回调函数。参数device是设备相关信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1762,6 +2153,39 @@ session.on('outputDeviceChange', (device) => { }); ``` +### on('commonCommand')10+ + +on(type: 'commonCommand', callback: (command: string, args: {[key: string]: Object}) => void): void + +设置自定义控制命令变化的监听器。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持事件`'commonCommand'`:当自定义控制命令变化时,触发该事件。 | +| callback | (commonCommand: string, args: {[key:string]: Object}) => void | 是 | 回调函数,commonCommand为变化的自定义控制命令名,args为自定义控制命令的参数。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**示例:** + +```js +session.on('commonCommand', (commonCommand, args) => { + console.info(`OnCommonCommand, the command is ${commonCommand}, args: ${JSON.stringify(args)}`); +}); +``` + ### off('play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind') off(type: 'play' | 'pause' | 'stop' | 'playNext' | 'playPrevious' | 'fastForward' | 'rewind', callback?: () => void): void @@ -1770,6 +2194,8 @@ off(type: 'play' | 'pause' | 'stop' | 'playNext' | 'playPrevious' | 'fastForward **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1778,7 +2204,7 @@ off(type: 'play' | 'pause' | 'stop' | 'playNext' | 'playPrevious' | 'fastForward | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1805,6 +2231,8 @@ off(type: 'seek', callback?: (time: number) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1813,7 +2241,7 @@ off(type: 'seek', callback?: (time: number) => void): void | callback | (time: number) => void | 否 | 回调函数,参数time是时间节点,单位为毫秒。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1834,6 +2262,8 @@ off(type: 'setSpeed', callback?: (speed: number) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1842,7 +2272,7 @@ off(type: 'setSpeed', callback?: (speed: number) => void): void | callback | (speed: number) => void | 否 | 回调函数,参数speed是播放倍速。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1863,6 +2293,8 @@ off(type: 'setLoopMode', callback?: (mode: LoopMode) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1871,7 +2303,7 @@ off(type: 'setLoopMode', callback?: (mode: LoopMode) => void): void | callback | (mode: [LoopMode](#loopmode)) => void | 否 | 回调函数,参数mode是循环模式。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1892,6 +2324,8 @@ off(type: 'toggleFavorite', callback?: (assetId: string) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1900,7 +2334,7 @@ off(type: 'toggleFavorite', callback?: (assetId: string) => void): void | callback | (assetId: string) => void | 否 | 回调函数,参数assetId是媒体ID。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1913,6 +2347,37 @@ off(type: 'toggleFavorite', callback?: (assetId: string) => void): void session.off('toggleFavorite'); ``` +### off('skipToQueueItem')10+ + +off(type: 'skipToQueueItem', callback?: (itemId: number) => void): void + +取消监听播放列表单项选中的事件 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| type | string | 是 | 关闭对应的监听事件,支持关闭事件`'skipToQueueItem'`。 | +| callback | (itemId: number) => void | 否 | 回调函数,参数itemId是播放列表单项ID。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +session.off('skipToQueueItem'); +``` + ### off('handleKeyEvent') off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void @@ -1921,6 +2386,8 @@ off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1929,7 +2396,7 @@ off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | 否 | 回调函数,参数event是按键事件。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1950,6 +2417,8 @@ off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1958,7 +2427,7 @@ off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | 否 | 回调函数,参数device是设备相关信息。
当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -1972,6 +2441,37 @@ session.off('outputDeviceChange'); ``` +### off('commonCommand')10+ + +off(type: 'commonCommand', callback?: (commonCommand: string, args: {[key:string]: Object}) => void): void + +取消监听自定义控制命令的变化。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| type | string | 是 | 取消对应的监听事件,支持事件`'commonCommand'`。 | +| callback | (commonCommand: string, args: {[key:string]: Object}) => void | 否 | 回调函数,参数commonCommand是变化的自定义控制命令名,args为自定义控制命令的参数。
该参数为可选参数,若不填写该参数,则认为取消所有对commonCommand事件的监听。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**示例:** + +```js +session.off('commonCommand'); +``` + + ## AVSessionController @@ -2005,6 +2505,8 @@ getAVPlaybackState(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2012,7 +2514,7 @@ getAVPlaybackState(): Promise\ | Promise<[AVPlaybackState](#avplaybackstate)\> | Promise对象。返回播放状态对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2031,34 +2533,255 @@ controller.getAVPlaybackState().then((playbackState) => { ### getAVPlaybackState -getAVPlaybackState(callback: AsyncCallback\): void +getAVPlaybackState(callback: AsyncCallback\): void + +获取当前播放状态相关信息。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | 是 | 回调函数,返回当前播放状态对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**示例:** +```js +controller.getAVPlaybackState(function (err, playbackState) { + if (err) { + console.info(`GetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`GetAVPlaybackState : SUCCESS : state : ${playbackState.state}`); + } +}); +``` + +### getAVQueueItems10+ + +getAVQueueItems(): Promise\> + +获取当前会话播放列表相关信息。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------------- | ----------------------------- | +| Promise\> | Promise对象。返回播放列表队列。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**示例:** +```js +controller.getAVQueueItems().then((items) => { + console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`); +}).catch((err) => { + console.info(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### getAVQueueItems10+ + +getAVQueueItems(callback: AsyncCallback\>): void + +获取当前播放列表相关信息。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback\> | 是 | 回调函数,返回播放列表队列。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**示例:** +```js +controller.getAVQueueItems(function (err, items) { + if (err) { + console.info(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`); + } +}); +``` + +### getAVQueueTitle10+ + +getAVQueueTitle(): Promise\ + +获取当前会话播放列表的名称。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------------- | +| Promise | Promise对象。返回播放列表名称。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**示例:** +```js +controller.getAVQueueTitle().then((title) => { + console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`); +}).catch((err) => { + console.info(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### getAVQueueTitle10+ + +getAVQueueTitle(callback: AsyncCallback\): void + +获取当前播放列表的名称。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回播放列表名称。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**示例:** +```js +controller.getAVQueueTitle(function (err, title) { + if (err) { + console.info(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`); + } +}); +``` + +### skipToQueueItem10+ + +skipToQueueItem(itemId: number): Promise\ + +设置指定播放列表单项的ID,发送给session端处理,session端可以选择对这个单项歌曲进行播放。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------------------- | +| itemId | number | 是 | 播放列表单项的ID值,用以表示选中的播放列表单项。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | --------------------------------------------------------------- | +| Promise | Promise对象。当播放列表单项ID设置成功,无返回结果,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**示例:** + +```js +let queueItemId = 0; +controller.skipToQueueItem(queueItemId).then(() => { + console.info('SkipToQueueItem successfully'); +}).catch((err) => { + console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### skipToQueueItem10+ + +skipToQueueItem(itemId: number, callback: AsyncCallback\): void -获取当前播放状态相关信息。结果通过callback异步回调方式返回。 +设置指定播放列表单项的ID,发送给session端处理,session端可以选择对这个单项歌曲进行播放。结果通过callback异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | 是 | 回调函数,返回当前播放状态对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| itemId | number | 是 | 播放列表单项的ID值,用以表示选中的播放列表单项。 | +| callback | AsyncCallback | 是 | 回调函数。当播放状态设置成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | | 6600101 | Session service exception. | | 6600102 | The session does not exist. | -| 6600103 | The session controller does not exist. | **示例:** + ```js -controller.getAVPlaybackState(function (err, playbackState) { +let queueItemId = 0; +controller.skipToQueueItem(queueItemId, function (err) { if (err) { - console.info(`GetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); + console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info(`GetAVPlaybackState : SUCCESS : state : ${playbackState.state}`); + console.info('SkipToQueueItem successfully'); } }); ``` @@ -2071,6 +2794,8 @@ getAVMetadata(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2078,7 +2803,7 @@ getAVMetadata(): Promise\ | Promise<[AVMetadata](#avmetadata)\> | Promise对象,返回会话元数据。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2103,6 +2828,8 @@ getAVMetadata(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2110,7 +2837,7 @@ getAVMetadata(callback: AsyncCallback\): void | callback | AsyncCallback<[AVMetadata](#avmetadata)\> | 是 | 回调函数,返回会话元数据。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2137,6 +2864,8 @@ getOutputDevice(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2144,7 +2873,7 @@ getOutputDevice(): Promise\ | Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise对象,返回播放设备信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2168,6 +2897,8 @@ getOutputDevice(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2175,7 +2906,7 @@ getOutputDevice(callback: AsyncCallback\): void | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | 是 | 回调函数,返回播放设备信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2202,6 +2933,8 @@ sendAVKeyEvent(event: KeyEvent): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2209,7 +2942,7 @@ sendAVKeyEvent(event: KeyEvent): Promise\ | event | [KeyEvent](js-apis-keyevent.md) | 是 | 按键事件。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2246,6 +2979,8 @@ sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2254,7 +2989,7 @@ sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当事件发送成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2287,6 +3022,8 @@ getLaunchAbility(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2294,7 +3031,7 @@ getLaunchAbility(): Promise\ | Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise对象,返回在[setLaunchAbility](#setlaunchability)保存的对象,包括应用的相关属性信息,如bundleName,abilityName,deviceId等。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2322,6 +3059,8 @@ getLaunchAbility(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2329,7 +3068,7 @@ getLaunchAbility(callback: AsyncCallback\): void | callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | 是 | 回调函数。返回在[setLaunchAbility](#setlaunchability)保存的对象,包括应用的相关属性信息,如bundleName,abilityName,deviceId等。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2359,6 +3098,8 @@ getRealPlaybackPositionSync(): number **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2366,7 +3107,7 @@ getRealPlaybackPositionSync(): number | number | 时间节点,毫秒数。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2387,6 +3128,8 @@ isActive(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2394,7 +3137,7 @@ isActive(): Promise\ | Promise | Promise对象,返回会话是否为激活状态,true表示被激活,false表示禁用。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2420,6 +3163,8 @@ isActive(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2427,7 +3172,7 @@ isActive(callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数,返回会话是否为激活状态,true表示被激活,false表示禁用。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2455,6 +3200,8 @@ destroy(): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2462,7 +3209,7 @@ destroy(): Promise\ | Promise | Promise对象。当控制器销毁成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2487,6 +3234,8 @@ destroy(callback: AsyncCallback\): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2494,7 +3243,7 @@ destroy(callback: AsyncCallback\): void | callback | AsyncCallback | 是 | 回调函数。当控制器销毁成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2521,6 +3270,8 @@ getValidCommands(): Promise\> **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **返回值:** | 类型 | 说明 | @@ -2528,7 +3279,7 @@ getValidCommands(): Promise\> | Promise\> | Promise对象。返回有效命令的集合。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2554,6 +3305,8 @@ getValidCommands(callback: AsyncCallback\>): void **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2561,7 +3314,7 @@ getValidCommands(callback: AsyncCallback\>): void | callback | AsyncCallback\\> | 是 | 回调函数,返回有效命令的集合。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2589,6 +3342,8 @@ sendControlCommand(command: AVControlCommand): Promise\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2602,7 +3357,7 @@ sendControlCommand(command: AVControlCommand): Promise\ | Promise | Promise对象。当命令发送成功,无返回结果,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | @@ -2642,6 +3397,8 @@ sendControlCommand(command: AVControlCommand, callback: AsyncCallback\): v **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2650,7 +3407,7 @@ sendControlCommand(command: AVControlCommand, callback: AsyncCallback\): v | callback | AsyncCallback | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------- | @@ -2684,6 +3441,93 @@ controller.sendControlCommand(avCommand, function (err) { }); ``` +### sendCommonCommand10+ + +sendCommonCommand(command: string, args: {[key: string]: Object}): Promise\ + +通过会话控制器发送自定义控制命令到其对应的会话。结果通过Promise异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ------------------------------ | +| command | string | 是 | 需要设置的自定义控制命令的名称 | +| args | {[key: string]: any} | 是 | 需要传递的控制命令键值对 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise | Promise对象。当命令发送成功,无返回结果,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | + +**示例:** + +```js +let commandName = "my_command"; +let args = { + command : "This is my command" +} +await controller.sendCommonCommand(commandName, args).catch((err) => { + console.info(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`); +}) +``` + +### sendCommonCommand10+ + +sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback\): void + +通过会话控制器发送自定义命令到其对应的会话。结果通过callback异步回调方式返回。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ------------------------------ | +| command | string | 是 | 需要设置的自定义控制命令的名称 | +| args | {[key: string]: any} | 是 | 需要传递的控制命令键值对 | +| callback | AsyncCallback | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | + +**示例:** + +```js +let commandName = "my_command"; +let args = { + command : "This is my command" +} +controller.sendCommonCommand(commandName, args, (err) => { + if(err) { + console.info(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`); + } +}) +``` + ### on('metadataChange') on(type: 'metadataChange', filter: Array\ | 'all', callback: (data: AVMetadata) => void) @@ -2692,6 +3536,8 @@ on(type: 'metadataChange', filter: Array\ | 'all', callback: ( **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2701,7 +3547,7 @@ on(type: 'metadataChange', filter: Array\ | 'all', callback: ( | callback | (data: [AVMetadata](#avmetadata)) => void | 是 | 回调函数,参数data是变化后的元数据。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -2729,6 +3575,8 @@ on(type: 'playbackStateChange', filter: Array\ | 'all', c **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2738,7 +3586,7 @@ on(type: 'playbackStateChange', filter: Array\ | 'all', c | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | 是 | 回调函数,参数state是变化后的播放状态。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -2758,9 +3606,9 @@ controller.on('playbackStateChange', playbackFilter, (playbackState) => { }); ``` -### on('sessionEventChange')10+ +### on('sessionEvent')10+ -on(type: 'sessionEventChange', callback: (sessionEvent: string, args: {[key:string]: any}) => void): void +on(type: 'sessionEvent', callback: (sessionEvent: string, args: {[key:string]: Object}) => void): void 媒体控制器设置会话自定义事件变化的监听器。 @@ -2772,11 +3620,77 @@ on(type: 'sessionEventChange', callback: (sessionEvent: string, args: {[key:stri | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'sessionEventChange'`:当会话事件变化时,触发该事件。 | -| callback | (sessionEvent: string, args: {[key:string]: any}) => void | 是 | 回调函数,sessionEvent为变化的会话事件名,args为事件的参数。 | +| type | string | 是 | 事件回调类型,支持事件`'sessionEvent'`:当会话事件变化时,触发该事件。 | +| callback | (sessionEvent: string, args: {[key:string]: object}) => void | 是 | 回调函数,sessionEvent为变化的会话事件名,args为事件的参数。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**示例:** + +```js +controller.on('sessionEvent', (sessionEvent, args) => { + console.info(`OnSessionEvent, sessionEvent is ${sessionEvent}, args: ${JSON.stringify(args)}`); +}); +``` + +### on('queueItemsChange')10+ + +on(type: 'queueItemsChange', callback: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void + +媒体控制器设置会话自定义播放列表变化的监听器。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------------- | +| type | string | 是 | 事件回调类型,支持事件`'queueItemsChange'`:当session修改播放列表时,触发该事件。 | +| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | 是 | 回调函数,items为变化的播放列表。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | + +**示例:** + +```js +controller.on('queueItemsChange', (items) => { + console.info(`OnQueueItemsChange, items length is ${items.length}`); +}); +``` + +### on('queueTitleChange')10+ + +on(type: 'queueTitleChange', callback: (title: string) => void): void + +媒体控制器设置会话自定义播放列表的名称变化的监听器。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------------------------------------------------------------------- | +| type | string | 是 | 事件回调类型,支持事件`'queueTitleChange'`:当session修改播放列表名称时,触发该事件。 | +| callback | (title: string) => void | 是 | 回调函数,title为变化的播放列表名称。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -2786,8 +3700,8 @@ on(type: 'sessionEventChange', callback: (sessionEvent: string, args: {[key:stri **示例:** ```js -controller.on('sessionEventChange', (sessionEvent, args) => { - console.info(`OnSessionEventChange, sessionEvent is ${sessionEvent}, args: ${JSON.stringify(args)}`); +controller.on('queueTitleChange', (title) => { + console.info(`queueTitleChange, title is ${title}`); }); ``` @@ -2799,6 +3713,8 @@ on(type: 'sessionDestroy', callback: () => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2807,7 +3723,7 @@ on(type: 'sessionDestroy', callback: () => void) | callback | () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则为错误对象。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -2830,6 +3746,8 @@ on(type: 'activeStateChange', callback: (isActive: boolean) => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2838,7 +3756,7 @@ on(type: 'activeStateChange', callback: (isActive: boolean) => void) | callback | (isActive: boolean) => void | 是 | 回调函数。参数isActive表示会话是否被激活。true表示被激活,false表示禁用。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ----------------------------- | @@ -2861,6 +3779,8 @@ on(type: 'validCommandChange', callback: (commands: Array\ **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2869,7 +3789,7 @@ on(type: 'validCommandChange', callback: (commands: Array\ | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | 是 | 回调函数。参数commands是有效命令的集合。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -2893,6 +3813,8 @@ on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): vo **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2901,7 +3823,7 @@ on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): vo | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | 是 | 回调函数,参数device是设备相关信息。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ----------------------- | @@ -2924,6 +3846,8 @@ off(type: 'metadataChange', callback?: (data: AVMetadata) => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2932,7 +3856,7 @@ off(type: 'metadataChange', callback?: (data: AVMetadata) => void) | callback | (data: [AVMetadata](#avmetadata)) => void | 否 | 回调函数,参数data是变化后的元数据。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -2952,6 +3876,8 @@ off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2960,7 +3886,7 @@ off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void) | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | 否 | 回调函数,参数state是变化后的播放状态。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -2972,11 +3898,11 @@ off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void) controller.off('playbackStateChange'); ``` -### off('sessionEventChange')10+ +### off('sessionEvent')10+ -off(type: 'sessionEventChange', callback?: (sessionEvent: string, args: {[key:string]: any}) => void): void +off(type: 'sessionEvent', callback?: (sessionEvent: string, args: {[key:string]: Obejct}) => void): void -控制器取消监听播放状态变化的事件。 +控制器取消监听会话事件的变化通知。 **系统能力:** SystemCapability.Multimedia.AVSession.Core @@ -2986,11 +3912,71 @@ off(type: 'sessionEventChange', callback?: (sessionEvent: string, args: {[key:st | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| type | string | 是 | 取消对应的监听事件,支持事件`'sessionEventChange'`。 | -| callback | (sessionEvent: string, args: {[key:string]: any}) => void | 否 | 回调函数,参数sessionEvent是变化的事件名,args为事件的参数。
该参数为可选参数,若不填写该参数,则认为取消所有对sessionEventChange事件的监听。 | +| type | string | 是 | 取消对应的监听事件,支持事件`'sessionEvent'`。 | +| callback | (sessionEvent: string, args: {[key:string]: object}) => void | 否 | 回调函数,参数sessionEvent是变化的事件名,args为事件的参数。
该参数为可选参数,若不填写该参数,则认为取消所有对sessionEvent事件的监听。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**示例:** + +```js +controller.off('sessionEvent'); +``` + +### off('queueItemsChange')10+ + +off(type: 'queueItemsChange', callback?: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void + +控制器取消监听播放列表变化的事件。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------- | +| type | string | 是 | 取消对应的监听事件,支持事件`'queueItemsChange'`。 | +| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | 否 | 回调函数,参数items是变化的播放列表。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | + +**错误码:** +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------- | +| 6600101 | Session service exception. | + +**示例:** + +```js +controller.off('queueItemsChange'); +``` + +### off('queueTitleChange')10+ + +off(type: 'queueTitleChange', callback?: (title: string) => void): void + +控制器取消监听播放列表名称变化的事件。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------------------------------------------------------------------------------------------- | +| type | string | 是 | 取消对应的监听事件,支持事件`'queueTitleChange'`。 | +| callback | (title: string) => void | 否 | 回调函数,参数items是变化的播放列表名称。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -2999,7 +3985,7 @@ off(type: 'sessionEventChange', callback?: (sessionEvent: string, args: {[key:st **示例:** ```js -controller.off('sessionEventChange'); +controller.off('queueTitleChange'); ``` ### off('sessionDestroy') @@ -3010,6 +3996,8 @@ off(type: 'sessionDestroy', callback?: () => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -3018,7 +4006,7 @@ off(type: 'sessionDestroy', callback?: () => void) | callback | () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -3038,6 +4026,8 @@ off(type: 'activeStateChange', callback?: (isActive: boolean) => void) **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -3046,7 +4036,7 @@ off(type: 'activeStateChange', callback?: (isActive: boolean) => void) | callback | (isActive: boolean) => void | 否 | 回调函数。参数isActive表示会话是否被激活。true表示被激活,false表示禁用。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -3066,6 +4056,8 @@ off(type: 'validCommandChange', callback?: (commands: Array\) => void | 否 | 回调函数。参数commands是有效命令的集合。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -3094,6 +4086,8 @@ off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -3102,7 +4096,7 @@ off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | 否 | 回调函数,参数device是设备相关信息。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimedia.avsession(多媒体会话)错误码](../errorcodes/errorcode-avsession.md)。 +以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 | 错误码ID | 错误信息 | | -------- | ---------------- | @@ -3135,6 +4129,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口。 + | 名称 | 类型 | 说明 | | ----- | ------ | ---- | | audio | string | 音频 | @@ -3164,6 +4160,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 说明 | | -------------- | ------ | ------------ | | play | string | 播放 | @@ -3184,6 +4182,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 必填 | 说明 | | --------- | ------------------------------------------------- | ---- | -------------- | | command | [AVControlCommandType](#avcontrolcommandtype) | 是 | 命令 | @@ -3195,6 +4195,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 必填 | 说明 | | --------------- |-------------------------| ---- |---------------------------------------------------------------------| | assetId | string | 是 | 媒体ID。 | @@ -3213,12 +4215,42 @@ controller.off('outputDeviceChange'); | previousAssetId | string | 否 | 上一首媒体ID。 | | nextAssetId | string | 否 | 下一首媒体ID。 | +## AVMediaDescription10+ + +播放列表媒体元数据的相关属性。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ----------------------- | ---- | ----------------------- | +| mediaId | string | 是 | 播放列表媒体ID。 | +| title | string | 否 | 播放列表媒体标题。 | +| subtitle | string | 否 | 播放列表媒体子标题。 | +| description | string | 否 | 播放列表媒体描述的文本。 | +| icon | image.PixelMap | 否 | 播放列表媒体图片像素数据。 | +| iconUri | string | 否 | 播放列表媒体图片路径地址。 | +| extras | {[key: string]: any} | 否 | 播放列表媒体额外字段。 | +| mediaUri | string | 否 | 播放列表媒体URI。 | + +## AVQueueItem10+ + +播放列表中单项的相关属性。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------------ | ---- | --------------------------- | +| itemId | number | 是 | 播放列表中单项的ID。 | +| description | [AVMediaDescription](#avmediadescription10) | 是 | 播放列表中单项的媒体元数据。 | + ## AVPlaybackState 媒体播放状态的相关属性。 **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 必填 | 说明 | | ------------ | ------------------------------------- | ---- | ------- | | state | [PlaybackState](#playbackstate) | 否 | 播放状态 | @@ -3234,6 +4266,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | ------------------ | | elapsedTime | number | 是 | 已用时间,单位毫秒(ms)。 | @@ -3245,6 +4279,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 类型 | 必填 | 说明 | | ---------- | -------------- | ---- | ---------------------- | | isRemote | boolean | 是 | 设备是否连接。 | @@ -3257,6 +4293,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 值 | 说明 | | --------------------------- | ---- | ----------- | | PLAYBACK_STATE_INITIAL | 0 | 初始状态 | @@ -3274,6 +4312,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 值 | 说明 | | ------------------ | ---- | -------- | | LOOP_MODE_SEQUENCE | 0 | 顺序播放 | @@ -3287,6 +4327,8 @@ controller.off('outputDeviceChange'); **系统能力:** SystemCapability.Multimedia.AVSession.Core +**系统接口:** 该接口为系统接口 + | 名称 | 值 | 说明 | | ------------------------------ | ------- | ------------------------------- | | ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception. | 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 605da9955596508dd7fa5bf8417aa8e3b2d05486..ca460869b665fa549a3fca272acd283b167fd9ca 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -161,7 +161,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击后跳转的界面。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | @@ -253,7 +253,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。 | @@ -339,7 +339,7 @@ stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): vo | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | **示例**: @@ -395,7 +395,7 @@ stopBackgroundRunning(context: Context): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | **返回值**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md index 95c477c34d8fecf0b0c1a51e2bb36490c4c677a6..5de930534fc4eb5263a316ea122fa23c60820b8e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -203,7 +203,7 @@ getHardwareUnitPowerValue(type: ConsumptionType): number ```js try { var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); - console.info('battery statistics percent of hardware is: ' + percent); + console.info('battery statistics value of hardware is: ' + value); } catch(err) { console.error('get battery statistics percent of hardware failed, err: ' + err); } @@ -243,7 +243,7 @@ getHardwareUnitPowerPercent(type: ConsumptionType): number ```js try { - var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + var percent = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); console.info('battery statistics percent of hardware is: ' + percent); } catch(err) { console.error('get battery statistics percent of hardware failed, err: ' + err); diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md index d2881854c8714b1daaa7b23a01e83744909fc750..1c8b02dde9ca35f07e7693d51a162ebc3de0b063 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @@ -3,8 +3,8 @@ 蓝牙模块提供了基础的传统蓝牙能力以及BLE的扫描、广播等功能。 > **说明:** -> > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 从API Version 9开始,该接口不再维护,推荐使用新接口[bluetoothManager](js-apis-bluetoothManager.md)。 @@ -15,12 +15,16 @@ import bluetooth from '@ohos.bluetooth'; ``` -## bluetooth.enableBluetooth8+ +## bluetooth.enableBluetooth8+(deprecated) enableBluetooth(): boolean 开启蓝牙。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.enableBluetooth](js-apis-bluetoothManager.md#bluetoothmanagerenablebluetooth)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -38,12 +42,16 @@ let enable = bluetooth.enableBluetooth(); ``` -## bluetooth.disableBluetooth8+ +## bluetooth.disableBluetooth8+(deprecated) disableBluetooth(): boolean 关闭蓝牙。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.disableBluetooth](js-apis-bluetoothManager.md#bluetoothmanagerdisablebluetooth)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -61,12 +69,16 @@ let disable = bluetooth.disableBluetooth(); ``` -## bluetooth.getLocalName8+ +## bluetooth.getLocalName8+(deprecated) getLocalName(): string 获取蓝牙本地设备名称。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getLocalName](js-apis-bluetoothManager.md#bluetoothmanagergetlocalname)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -84,12 +96,16 @@ let localName = bluetooth.getLocalName(); ``` -## bluetooth.getState +## bluetooth.getState(deprecated) getState(): BluetoothState 获取蓝牙开关状态。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getState](js-apis-bluetoothManager.md#bluetoothmanagergetstate)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -107,12 +123,16 @@ let state = bluetooth.getState(); ``` -## bluetooth.getBtConnectionState +## bluetooth.getBtConnectionState(deprecated) getBtConnectionState(): ProfileConnectionState 获取蓝牙设备的Profile连接状态。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getBtConnectionState](js-apis-bluetoothManager.md#bluetoothmanagergetbtconnectionstate)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -130,12 +150,16 @@ let connectionState = bluetooth.getBtConnectionState(); ``` -## bluetooth.setLocalName8+ +## bluetooth.setLocalName8+(deprecated) setLocalName(name: string): boolean 设置蓝牙本地设备名称。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.setLocalName](js-apis-bluetoothManager.md#bluetoothmanagersetlocalname)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -159,12 +183,16 @@ let ret = bluetooth.setLocalName('device_name'); ``` -## bluetooth.pairDevice +## bluetooth.pairDevice(deprecated) pairDevice(deviceId: string): boolean 发起蓝牙配对。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.pairDevice](js-apis-bluetoothManager.md#bluetoothmanagerpairdevice)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -189,12 +217,16 @@ let result = bluetooth.pairDevice("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getProfileConnState8+ +## bluetooth.getProfileConnState8+(deprecated) getProfileConnState(profileId: ProfileId): ProfileConnectionState 获取profile的连接状态。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getProfileConnectionState](js-apis-bluetoothManager.md#bluetoothmanagergetprofileconnectionstate)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -218,12 +250,16 @@ let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOUR ``` -## bluetooth.cancelPairedDevice8+ +## bluetooth.cancelPairedDevice8+(deprecated) cancelPairedDevice(deviceId: string): boolean 删除配对的远程设备。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.cancelPairedDevice](js-apis-bluetoothManager.md#bluetoothmanagercancelpaireddevice)替代。 + **系统接口**:此接口为系统接口。 **需要权限**:ohos.permission.DISCOVER_BLUETOOTH @@ -249,12 +285,16 @@ let result = bluetooth.cancelPairedDevice("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getRemoteDeviceName8+ +## bluetooth.getRemoteDeviceName8+(deprecated) getRemoteDeviceName(deviceId: string): string 获取对端蓝牙设备的名称。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getRemoteDeviceName](js-apis-bluetoothManager.md#bluetoothmanagergetremotedevicename)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -278,12 +318,16 @@ let remoteDeviceName = bluetooth.getRemoteDeviceName("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getRemoteDeviceClass8+ +## bluetooth.getRemoteDeviceClass8+(deprecated) getRemoteDeviceClass(deviceId: string): DeviceClass 获取对端蓝牙设备的类别。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getRemoteDeviceClass](js-apis-bluetoothManager.md#bluetoothmanagergetremotedeviceclass)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -307,12 +351,16 @@ let remoteDeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getPairedDevices8+ +## bluetooth.getPairedDevices8+(deprecated) getPairedDevices(): Array<string> 获取蓝牙配对列表。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getPairedDevices](js-apis-bluetoothManager.md#bluetoothmanagergetpaireddevices)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -330,12 +378,16 @@ let devices = bluetooth.getPairedDevices(); ``` -## bluetooth.setBluetoothScanMode8+ +## bluetooth.setBluetoothScanMode8+(deprecated) setBluetoothScanMode(mode: ScanMode, duration: number): boolean 设置蓝牙扫描模式,可以被远端设备发现。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.setBluetoothScanMode](js-apis-bluetoothManager.md#bluetoothmanagersetbluetoothscanmode)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -361,12 +413,16 @@ let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECT ``` -## bluetooth.getBluetoothScanMode8+ +## bluetooth.getBluetoothScanMode8+(deprecated) getBluetoothScanMode(): ScanMode 获取蓝牙扫描模式。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getBluetoothScanMode](js-apis-bluetoothManager.md#bluetoothmanagergetbluetoothscanmode)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -384,12 +440,16 @@ let scanMode = bluetooth.getBluetoothScanMode(); ``` -## bluetooth.startBluetoothDiscovery8+ +## bluetooth.startBluetoothDiscovery8+(deprecated) startBluetoothDiscovery(): boolean 开启蓝牙扫描,可以发现远端设备。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.startBluetoothDiscovery](js-apis-bluetoothManager.md#bluetoothmanagerstartbluetoothdiscovery)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH 和 ohos.permission.LOCATION **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -412,12 +472,16 @@ let result = bluetooth.startBluetoothDiscovery(); ``` -## bluetooth.stopBluetoothDiscovery8+ +## bluetooth.stopBluetoothDiscovery8+(deprecated) stopBluetoothDiscovery(): boolean 关闭蓝牙扫描。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.stopBluetoothDiscovery](js-apis-bluetoothManager.md#bluetoothmanagerstopbluetoothdiscovery)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -435,12 +499,16 @@ let result = bluetooth.stopBluetoothDiscovery(); ``` -## bluetooth.setDevicePairingConfirmation8+ +## bluetooth.setDevicePairingConfirmation8+(deprecated) setDevicePairingConfirmation(device: string, accept: boolean): boolean 设置设备配对请求确认。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.setDevicePairingConfirmation](js-apis-bluetoothManager.md#bluetoothmanagersetdevicepairingconfirmation)替代。 + **需要权限**:ohos.permission.MANAGE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -470,12 +538,16 @@ bluetooth.on("pinRequired", onReceivePinRequiredEvent); ``` -## bluetooth.on('bluetoothDeviceFind')8+ +## bluetooth.on('bluetoothDeviceFind')8+(deprecated) on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void 订阅蓝牙设备发现上报事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.on('bluetoothDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanageronbluetoothdevicefind)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -501,12 +573,16 @@ bluetooth.on('bluetoothDeviceFind', onReceiveEvent); ``` -## bluetooth.off('bluetoothDeviceFind')8+ +## bluetooth.off('bluetoothDeviceFind')8+(deprecated) off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void 取消订阅蓝牙设备发现上报事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.off('bluetoothDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanageroffbluetoothdevicefind)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -533,12 +609,16 @@ bluetooth.off('bluetoothDeviceFind', onReceiveEvent); ``` -## bluetooth.on('pinRequired')8+ +## bluetooth.on('pinRequired')8+(deprecated) on(type: "pinRequired", callback: Callback<PinRequiredParam>): void 订阅远端蓝牙设备的配对请求事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.on('pinRequired')](js-apis-bluetoothManager.md#bluetoothmanageronpinrequired)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -564,12 +644,16 @@ bluetooth.on('pinRequired', onReceiveEvent); ``` -## bluetooth.off('pinRequired')8+ +## bluetooth.off('pinRequired')8+(deprecated) off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void 取消订阅远端蓝牙设备的配对请求事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.off('pinRequired')](js-apis-bluetoothManager.md#bluetoothmanageroffpinrequired)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -596,12 +680,16 @@ bluetooth.off('pinRequired', onReceiveEvent); ``` -## bluetooth.on('bondStateChange')8+ +## bluetooth.on('bondStateChange')8+(deprecated) on(type: "bondStateChange", callback: Callback<BondStateParam>): void 订阅蓝牙配对状态改变事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.on('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageronbondstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -627,12 +715,16 @@ bluetooth.on('bondStateChange', onReceiveEvent); ``` -## bluetooth.off('bondStateChange')8+ +## bluetooth.off('bondStateChange')8+(deprecated) off(type: "bondStateChange", callback?: Callback<BondStateParam>): void 取消订阅蓝牙配对状态改变事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.off('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffbondstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -659,12 +751,16 @@ bluetooth.off('bondStateChange', onReceiveEvent); ``` -## bluetooth.on('stateChange')8+ +## bluetooth.on('stateChange')8+(deprecated) on(type: "stateChange", callback: Callback<BluetoothState>): void 订阅蓝牙连接状态改变事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.on('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageronstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -690,12 +786,16 @@ bluetooth.on('stateChange', onReceiveEvent); ``` -## bluetooth.off('stateChange')8+ +## bluetooth.off('stateChange')8+(deprecated) off(type: "stateChange", callback?: Callback<BluetoothState>): void 取消订阅蓝牙连接状态改变事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.off('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -722,12 +822,16 @@ bluetooth.off('stateChange', onReceiveEvent); ``` -## bluetooth.sppListen8+ +## bluetooth.sppListen8+(deprecated) sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void 创建一个服务端监听Socket。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppListen](js-apis-bluetoothManager.md#bluetoothmanagerspplisten)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -757,12 +861,16 @@ bluetooth.sppListen('server1', sppOption, serverSocket); ``` -## bluetooth.sppAccept8+ +## bluetooth.sppAccept8+(deprecated) sppAccept(serverSocket: number, callback: AsyncCallback<number>): void 服务端监听socket等待客户端连接。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppAccept](js-apis-bluetoothManager.md#bluetoothmanagersppaccept)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -796,12 +904,16 @@ bluetooth.sppAccept(serverNumber, acceptClientSocket); ``` -## bluetooth.sppConnect8+ +## bluetooth.sppConnect8+(deprecated) sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void 客户端向远端设备发起spp连接。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppConnect](js-apis-bluetoothManager.md#bluetoothmanagersppconnect)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -832,12 +944,16 @@ bluetooth.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket); ``` -## bluetooth.sppCloseServerSocket8+ +## bluetooth.sppCloseServerSocket8+(deprecated) sppCloseServerSocket(socket: number): void 关闭服务端监听Socket,入参socket由sppListen接口返回。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppCloseServerSocket](js-apis-bluetoothManager.md#bluetoothmanagersppcloseserversocket)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -861,12 +977,16 @@ bluetooth.sppCloseServerSocket(serverNumber); ``` -## bluetooth.sppCloseClientSocket8+ +## bluetooth.sppCloseClientSocket8+(deprecated) sppCloseClientSocket(socket: number): void 关闭客户端socket,入参socket由sppAccept或sppConnect接口获取。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppCloseClientSocket](js-apis-bluetoothManager.md#bluetoothmanagersppcloseclientsocket)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -892,12 +1012,16 @@ bluetooth.sppCloseClientSocket(clientNumber); ``` -## bluetooth.sppWrite8+ +## bluetooth.sppWrite8+(deprecated) sppWrite(clientSocket: number, data: ArrayBuffer): boolean 通过socket向远端发送数据,入参clientSocket由sppAccept或sppConnect接口获取 。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.sppWrite](js-apis-bluetoothManager.md#bluetoothmanagersppwrite)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -937,10 +1061,14 @@ if (ret) { ``` -## bluetooth.on('sppRead')8+ +## bluetooth.on('sppRead')8+(deprecated) on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.on('sppRead')](js-apis-bluetoothManager.md#bluetoothmanageronsppread)替代。 + 订阅spp读请求事件,入参clientSocket由sppAccept或sppConnect接口获取。 **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -977,12 +1105,16 @@ bluetooth.on('sppRead', clientNumber, dataRead); ``` -## bluetooth.off('sppRead')8+ +## bluetooth.off('sppRead')8+(deprecated) off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void 取消订阅spp读请求事件,入参clientSocket由sppAccept或sppConnect接口获取。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.off('sppRead')](js-apis-bluetoothManager.md#bluetoothmanageroffsppread)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1013,12 +1145,16 @@ bluetooth.off('sppRead', clientNumber); ``` -## bluetooth.getProfile8+ +## bluetooth.getProfile8+(deprecated) getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile 通过ProfileId,获取profile的对象实例。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.getProfileInstance](js-apis-bluetoothManager.md#bluetoothmanagergetprofileinstance)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1039,41 +1175,19 @@ getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfi let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ``` -## bluetooth.getProfileInst9+ - -getProfileInst(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile - -通过ProfileId,获取profile的对象实例,API9新增了HidHostProfile,PanProfile。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | --------- | ---- | ------------------------------------- | -| profileId | [ProfileId](#ProfileId) | 是 | 表示profile的枚举值,例如:PROFILE_A2DP_SOURCE。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| [A2dpSourceProfile](#a2dpsourceprofile)或 [HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile)或[HidHostProfile](#hidhostprofile)或[PanProfile](#panprofile) | 对应的profile的对象实例,当前支持A2dpSourceProfile/HandsFreeAudioGatewayProfile/HidHostProfile/PanProfile。 | - -**示例:** - -```js -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST); -``` - ## bluetooth.BLE -### bluetooth.BLE.createGattServer +### bluetooth.BLE.createGattServer(deprecated) createGattServer(): GattServer 创建一个可使用的GattServer实例。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.createGattServer](js-apis-bluetoothManager.md#bluetoothmanagerblecreategattserver)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **返回值:** @@ -1089,12 +1203,16 @@ let gattServer = bluetooth.BLE.createGattServer(); ``` -### bluetooth.BLE.createGattClientDevice +### bluetooth.BLE.createGattClientDevice(deprecated) createGattClientDevice(deviceId: string): GattClientDevice 创建一个可使用的GattClientDevice实例。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.createGattClientDevice](js-apis-bluetoothManager.md#bluetoothmanagerblecreategattclientdevice)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1116,12 +1234,16 @@ let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); ``` -### bluetooth.BLE.getConnectedBLEDevices +### bluetooth.BLE.getConnectedBLEDevices(deprecated) getConnectedBLEDevices(): Array<string> 获取和当前设备连接的BLE设备。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.getConnectedBLEDevices](js-apis-bluetoothManager.md#bluetoothmanagerblegetconnectedbledevices)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1139,12 +1261,16 @@ let result = bluetooth.BLE.getConnectedBLEDevices(); ``` -### bluetooth.BLE.startBLEScan +### bluetooth.BLE.startBLEScan(deprecated) startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void 发起BLE扫描流程。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.startBLEScan](js-apis-bluetoothManager.md#bluetoothmanagerblestartblescan)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH 和 ohos.permission.MANAGE_BLUETOOTH 和 ohos.permission.LOCATION **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1182,12 +1308,16 @@ bluetooth.BLE.startBLEScan( ``` -### bluetooth.BLE.stopBLEScan +### bluetooth.BLE.stopBLEScan(deprecated) stopBLEScan(): void 停止BLE扫描流程。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.stopBLEScan](js-apis-bluetoothManager.md#bluetoothmanagerblestopblescan)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1203,12 +1333,16 @@ bluetooth.BLE.stopBLEScan(); ``` -### bluetooth.BLE.on('BLEDeviceFind') +### bluetooth.BLE.on('BLEDeviceFind')(deprecated) on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void 订阅BLE设备发现上报事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.on('BLEDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanagerbleonbledevicefind)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1234,12 +1368,16 @@ bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent); ``` -### bluetooth.BLE.off('BLEDeviceFind') +### bluetooth.BLE.off('BLEDeviceFind')(deprecated) off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void 取消订阅BLE设备发现上报事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLE.off('BLEDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanagerbleoffbledevicefind)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1271,12 +1409,16 @@ bluetooth.BLE.off('BLEDeviceFind', onReceiveEvent); profile基类。 -### getConnectionDevices8+ +### getConnectionDevices8+(deprecated) getConnectionDevices(): Array<string> 获取已连接设备列表。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BaseProfile.getConnectionDevices](js-apis-bluetoothManager.md#getconnectiondevices)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1294,12 +1436,16 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as b let retArray = a2dpSrc.getConnectionDevices(); ``` -### getDeviceState8+ +### getDeviceState8+(deprecated) getDeviceState(device: string): ProfileConnectionState 获取设备profile的连接状态。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BaseProfile.getDeviceState](js-apis-bluetoothManager.md#getdevicestate)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1328,12 +1474,16 @@ let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); 使用A2dpSourceProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 -### connect8+ +### connect8+(deprecated) connect(device: string): boolean 发起设备的A2dp服务连接请求。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.A2dpSourceProfile.connect](js-apis-bluetoothManager.md#connect)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1358,12 +1508,16 @@ let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+(deprecated) disconnect(device: string): boolean 断开设备的a2dp服务连接。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.A2dpSourceProfile.disconnect](js-apis-bluetoothManager.md#disconnect)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1388,12 +1542,16 @@ let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` -### on('connectionStateChange')8+ +### on('connectionStateChange')8+(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void 订阅a2dp连接状态变化事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.A2dpSourceProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1418,12 +1576,16 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange')8+ +### off('connectionStateChange')8+(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void 取消订阅a2dp连接状态变化事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.A2dpSourceProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1449,12 +1611,16 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState8+ +### getPlayingState8+(deprecated) getPlayingState(device: string): PlayingState 获取设备的播放状态。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.A2dpSourceProfile.getPlayingState](js-apis-bluetoothManager.md#getplayingstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1482,12 +1648,16 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); 使用HandsFreeAudioGatewayProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 -### connect8+ +### connect8+(deprecated) connect(device: string): boolean 连接设备的HFP服务。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.HandsFreeAudioGatewayProfile.connect](js-apis-bluetoothManager.md#connect-1)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1513,12 +1683,16 @@ let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+(deprecated) disconnect(device: string): boolean 断开连接设备的HFP服务。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.HandsFreeAudioGatewayProfile.disconnect](js-apis-bluetoothManager.md#disconnect-1)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1544,12 +1718,16 @@ let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); ``` -### on('connectionStateChange')8+ +### on('connectionStateChange')8+(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void 订阅HFP连接状态变化事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.HandsFreeAudioGatewayProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange-1)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1575,12 +1753,16 @@ hfpAg.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange')8+ +### off('connectionStateChange')8+(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void 取消订阅HFP连接状态变化事件。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.HandsFreeAudioGatewayProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange-1)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 **参数:** @@ -1607,301 +1789,21 @@ hfpAg.off('connectionStateChange', onReceiveEvent); ``` -## HidHostProfile - -使用HidHostProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 - - -### connect9+ - -connect(device: string): boolean - -连接设备的HidHost服务。 - -**系统接口**:此接口为系统接口。 - -**需要权限**:ohos.permission.DISCOVER_BLUETOOTH - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| device | string | 是 | 远端设备地址。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------------- | -| boolean | 成功返回true,失败返回false。 | - -**示例:** - -```js -let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); -``` - - -### disconnect9+ - -disconnect(device: string): boolean - -断开连接设备的HidHost服务。 - -**系统接口**:此接口为系统接口。 - -**需要权限**:ohos.permission.DISCOVER_BLUETOOTH - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| device | string | 是 | 远端设备地址。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------------- | -| boolean | 成功返回true,失败返回false。 | - -**示例:** - -```js -let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); -``` - - -### on('connectionStateChange')9+ - -on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void - -订阅HidHost连接状态变化事件。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | - -**返回值:** - -无 - -**示例:** - -```js -function onReceiveEvent(data) { - console.info('hidHost state = '+ JSON.stringify(data)); -} -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -hidHost.on('connectionStateChange', onReceiveEvent); -``` - - -### off('connectionStateChange')9+ - -off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void - -取消订阅HidHost连接状态变化事件。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | -| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | - -**返回值:** - -无 - -**示例:** - -```js -function onReceiveEvent(data) { - console.info('hidHost state = '+ JSON.stringify(data)); -} -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -hidHost.on('connectionStateChange', onReceiveEvent); -hidHost.off('connectionStateChange', onReceiveEvent); -``` - - -## PanProfile - -使用PanProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 - - -### disconnect9+ - -disconnect(device: string): boolean - -断开连接设备的Pan服务。 - -**系统接口**:此接口为系统接口。 - -**需要权限**:ohos.permission.USE_BLUETOOTH - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| device | string | 是 | 远端设备地址。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------------- | -| boolean | 成功返回true,失败返回false。 | - -**示例:** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); -``` - - -### on('connectionStateChange')9+ - -on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void - -订阅Pan连接状态变化事件。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | - -**返回值:** - -无 - -**示例:** - -```js -function onReceiveEvent(data) { - console.info('pan state = '+ JSON.stringify(data)); -} -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -panProfile.on('connectionStateChange', onReceiveEvent); -``` - - -### off('connectionStateChange')9+ - -off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void - -取消订阅Pan连接状态变化事件。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | -| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | - -**返回值:** - -无 - -**示例:** - -```js -function onReceiveEvent(data) { - console.info('pan state = '+ JSON.stringify(data)); -} -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -panProfile.on('connectionStateChange', onReceiveEvent); -panProfile.off('connectionStateChange', onReceiveEvent); -``` - - -### setTethering9+ - -setTethering(enable: boolean): void - -设置网络共享状态。 - -**系统接口**:此接口为系统接口。 - -**需要权限**:ohos.permission.DISCOVER_BLUETOOTH - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| value | boolean | 是 | 是否设置蓝牙共享。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------------- | -| boolean | 成功返回true,失败返回false。 | - -**示例:** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.setTethering(true); -``` - - -### isTetheringOn9+ - -isTetheringOn(): boolean - -获取网络共享状态。 - -**系统接口**:此接口为系统接口。 - -**系统能力**:SystemCapability.Communication.Bluetooth.Core。 - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------------- | -| boolean | 网络共享开启返回true,网络共享关闭返回false。 | - -**示例:** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.isTetheringOn(); -``` - - ## GattServer server端类,使用server端方法之前需要创建该类的实例进行操作,通过createGattServer()方法构造此实例。 -### startAdvertising +### startAdvertising(deprecated) startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void 开始发送BLE广播。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.startAdvertising](js-apis-bluetoothManager.md#startadvertising)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1963,12 +1865,16 @@ gattServer.startAdvertising({ ``` -### stopAdvertising +### stopAdvertising(deprecated) stopAdvertising(): void 停止发送BLE广播。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.stopAdvertising](js-apis-bluetoothManager.md#stopadvertising)替代。 + **需要权限**:ohos.permission.DISCOVER_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -1985,12 +1891,16 @@ server.stopAdvertising(); ``` -### addService +### addService(deprecated) addService(service: GattService): boolean server端添加服务。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.addService](js-apis-bluetoothManager.md#addservice)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2044,12 +1954,16 @@ if (ret) { ``` -### removeService +### removeService(deprecated) removeService(serviceUuid: string): boolean 删除已添加的服务。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.removeService](js-apis-bluetoothManager.md#removeservice)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2074,12 +1988,16 @@ server.removeService('00001810-0000-1000-8000-00805F9B34FB'); ``` -### close +### close(deprecated) close(): void 关闭服务端功能,去注册server在协议栈的注册,调用该接口后[GattServer](#gattserver)实例将不能再使用。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.close](js-apis-bluetoothManager.md#close)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2092,12 +2010,16 @@ server.close(); ``` -### notifyCharacteristicChanged +### notifyCharacteristicChanged(deprecated) notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): boolean server端特征值发生变化时,主动通知已连接的client设备。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.notifyCharacteristicChanged](js-apis-bluetoothManager.md#notifycharacteristicchanged)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2137,12 +2059,16 @@ server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); ``` -### sendResponse +### sendResponse(deprecated) sendResponse(serverResponse: ServerResponse): boolean server端回复client端的读写请求。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.sendResponse](js-apis-bluetoothManager.md#sendresponse)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2184,12 +2110,16 @@ if (ret) { ``` -### on('characteristicRead') +### on('characteristicRead')(deprecated) on(type: "characteristicRead", callback: Callback<CharacteristicReadReq>): void server端订阅特征值读请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.on('characteristicRead')](js-apis-bluetoothManager.md#oncharacteristicread)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2232,12 +2162,16 @@ gattServer.on("characteristicRead", ReadCharacteristicReq); ``` -### off('characteristicRead') +### off('characteristicRead')(deprecated) off(type: "characteristicRead", callback?: Callback<CharacteristicReadReq>): void server端取消订阅特征值读请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.off('characteristicRead')](js-apis-bluetoothManager.md#offcharacteristicread)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2261,12 +2195,16 @@ gattServer.off("characteristicRead"); ``` -### on('characteristicWrite') +### on('characteristicWrite')(deprecated) on(type: "characteristicWrite", callback: Callback<CharacteristicWriteReq>): void server端订阅特征值写请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.on('characteristicWrite')](js-apis-bluetoothManager.md#oncharacteristicwrite)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2312,12 +2250,16 @@ gattServer.on("characteristicWrite", WriteCharacteristicReq); ``` -### off('characteristicWrite') +### off('characteristicWrite')(deprecated) off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteReq>): void server端取消订阅特征值写请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.off('characteristicWrite')](js-apis-bluetoothManager.md#offcharacteristicwrite)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2341,12 +2283,16 @@ gattServer.off("characteristicWrite"); ``` -### on('descriptorRead') +### on('descriptorRead')(deprecated) on(type: "descriptorRead", callback: Callback<DescriptorReadReq>): void server端订阅描述符读请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.on('descriptorRead')](js-apis-bluetoothManager.md#ondescriptorread)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2389,12 +2335,16 @@ gattServer.on("descriptorRead", ReadDescriptorReq); ``` -### off('descriptorRead') +### off('descriptorRead')(deprecated) off(type: "descriptorRead", callback?: Callback<DescriptorReadReq>): void server端取消订阅描述符读请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.off('descriptorRead')](js-apis-bluetoothManager.md#offdescriptorread)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2418,12 +2368,16 @@ gattServer.off("descriptorRead"); ``` -### on('descriptorWrite') +### on('descriptorWrite')(deprecated) on(type: "descriptorWrite", callback: Callback<DescriptorWriteReq>): void server端订阅描述符写请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.on('descriptorWrite')](js-apis-bluetoothManager.md#ondescriptorwrite)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2469,12 +2423,16 @@ gattServer.on("descriptorRead", WriteDescriptorReq); ``` -### off('descriptorWrite') +### off('descriptorWrite')(deprecated) off(type: "descriptorWrite", callback?: Callback<DescriptorWriteReq>): void server端取消订阅描述符写请求事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.off('descriptorWrite')](js-apis-bluetoothManager.md#offdescriptorwrite)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2498,12 +2456,16 @@ gattServer.off("descriptorWrite"); ``` -### on('connectStateChange') +### on('connectStateChange')(deprecated) on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void server端订阅BLE连接状态变化事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.on('connectStateChange')](js-apis-bluetoothManager.md#onconnectstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2532,12 +2494,16 @@ gattServer.on("connectStateChange", Connected); ``` -### off('connectStateChange') +### off('connectStateChange')(deprecated) off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void server端取消订阅BLE连接状态变化事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattServer.off('connectStateChange')](js-apis-bluetoothManager.md#offconnectstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2566,12 +2532,16 @@ gattServer.off("connectStateChange"); client端类,使用client端方法之前需要创建该类的实例进行操作,通过createGattClientDevice(deviceId: string)方法构造此实例。 -### connect +### connect(deprecated) connect(): boolean client端发起连接远端蓝牙低功耗设备。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.connect](js-apis-bluetoothManager.md#connect-3)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2590,12 +2560,16 @@ let ret = device.connect(); ``` -### disconnect +### disconnect(deprecated) disconnect(): boolean client端断开与远端蓝牙低功耗设备的连接。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.disconnect](js-apis-bluetoothManager.md#disconnect-4)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2614,12 +2588,16 @@ let ret = device.disconnect(); ``` -### close +### close(deprecated) close(): boolean 关闭客户端功能,注销client在协议栈的注册,调用该接口后[GattClientDevice](#gattclientdevice)实例将不能再使用。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.close](js-apis-bluetoothManager.md#close-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2640,12 +2618,16 @@ let ret = device.close(); -### getServices +### getServices(deprecated) getServices(callback: AsyncCallback<Array<GattService>>): void client端获取蓝牙低功耗设备的所有服务,即服务发现 。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getServices](js-apis-bluetoothManager.md#getservices)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2682,12 +2664,16 @@ device.getServices(getServices); ``` -### getServices +### getServices(deprecated) getServices(): Promise<Array<GattService>> client端获取蓝牙低功耗设备的所有服务,即服务发现。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getServices](js-apis-bluetoothManager.md#getservices-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2710,12 +2696,16 @@ device.getServices().then(result => { ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void client端读取蓝牙低功耗设备特定服务的特征值。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.readCharacteristicValue](js-apis-bluetoothManager.md#readcharacteristicvalue)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2764,12 +2754,16 @@ device.readCharacteristicValue(characteristic, readCcc); ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> client端读取蓝牙低功耗设备特定服务的特征值。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.readCharacteristicValue](js-apis-bluetoothManager.md#readcharacteristicvalue-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2810,12 +2804,16 @@ device.readCharacteristicValue(characteristic); ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void client端读取蓝牙低功耗设备特定的特征包含的描述符。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.readDescriptorValue](js-apis-bluetoothManager.md#readdescriptorvalue)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2854,12 +2852,16 @@ device.readDescriptorValue(descriptor, readDesc); ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> client端读取蓝牙低功耗设备特定的特征包含的描述符。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.readDescriptorValue](js-apis-bluetoothManager.md#readdescriptorvalue-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2890,12 +2892,16 @@ device.readDescriptorValue(descriptor); ``` -### writeCharacteristicValue +### writeCharacteristicValue(deprecated) writeCharacteristicValue(characteristic: BLECharacteristic): boolean client端向低功耗蓝牙设备写入特定的特征值。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.writeCharacteristicValue](js-apis-bluetoothManager.md#writecharacteristicvalue)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2940,12 +2946,16 @@ if (retWriteCcc) { ``` -### writeDescriptorValue +### writeDescriptorValue(deprecated) writeDescriptorValue(descriptor: BLEDescriptor): boolean client端向低功耗蓝牙设备特定的描述符写入二进制数据。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.writeDescriptorValue](js-apis-bluetoothManager.md#writedescriptorvalue)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -2981,12 +2991,16 @@ if (retWriteDesc) { ``` -### setBLEMtuSize +### setBLEMtuSize(deprecated) setBLEMtuSize(mtu: number): boolean client协商远端蓝牙低功耗设备的最大传输单元(Maximum Transmission Unit, MTU),调用[connect](#connect)接口连接成功后才能使用。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.setBLEMtuSize](js-apis-bluetoothManager.md#setblemtusize)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3011,12 +3025,16 @@ device.setBLEMtuSize(128); ``` -### setNotifyCharacteristicChanged +### setNotifyCharacteristicChanged(deprecated) setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): boolean 向服务端发送设置通知此特征值请求。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.setNotifyCharacteristicChanged](js-apis-bluetoothManager.md#setnotifycharacteristicchanged)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3054,12 +3072,16 @@ device.setNotifyCharacteristicChanged(characteristic, false); ``` -### on('BLECharacteristicChange') +### on('BLECharacteristicChange')(deprecated) on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void 订阅蓝牙低功耗设备的特征值变化事件。需要先调用setNotifyCharacteristicChanged接口才能接收server端的通知。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.on('BLECharacteristicChange')](js-apis-bluetoothManager.md#onblecharacteristicchange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3088,12 +3110,16 @@ device.on('BLECharacteristicChange', CharacteristicChange); ``` -### off('BLECharacteristicChange') +### off('BLECharacteristicChange')(deprecated) off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void 取消订阅蓝牙低功耗设备的特征值变化事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.off('BLECharacteristicChange')](js-apis-bluetoothManager.md#offblecharacteristicchange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3117,12 +3143,16 @@ device.off('BLECharacteristicChange'); ``` -### on('BLEConnectionStateChange') +### on('BLEConnectionStateChange')(deprecated) on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void client端订阅蓝牙低功耗设备的连接状态变化事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.on('BLEConnectionStateChange')](js-apis-bluetoothManager.md#onbleconnectionstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3150,12 +3180,16 @@ device.on('BLEConnectionStateChange', ConnectStateChanged); ``` -### off('BLEConnectionStateChange') +### off('BLEConnectionStateChange')(deprecated) off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void 取消订阅蓝牙低功耗设备的连接状态变化事件。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.off('BLEConnectionStateChange')](js-apis-bluetoothManager.md#offbleconnectionstatechange)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3179,12 +3213,16 @@ device.off('BLEConnectionStateChange'); ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(callback: AsyncCallback<string>): void client获取远端蓝牙低功耗设备名。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getDeviceName](js-apis-bluetoothManager.md#getdevicename)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3211,12 +3249,16 @@ let deviceName = gattClient.getDeviceName((err, data)=> { ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(): Promise<string> client获取远端蓝牙低功耗设备名。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getDeviceName](js-apis-bluetoothManager.md#getdevicename-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3239,12 +3281,16 @@ let deviceName = gattClient.getDeviceName().then((data) => { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(callback: AsyncCallback<number>): void client获取远端蓝牙低功耗设备的信号强度 (Received Signal Strength Indication, RSSI),调用[connect](#connect)接口连接成功后才能使用。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getRssiValue](js-apis-bluetoothManager.md#getrssivalue)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3272,12 +3318,16 @@ let rssi = gattClient.getRssiValue((err, data)=> { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(): Promise<number> client获取远端蓝牙低功耗设备的信号强度 (Received Signal Strength Indication, RSSI),调用[connect](#connect)接口连接成功后才能使用。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattClientDevice.getRssiValue](js-apis-bluetoothManager.md#getrssivalue-1)替代。 + **需要权限**:ohos.permission.USE_BLUETOOTH **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -3298,10 +3348,14 @@ let rssi = gattClient.getRssiValue().then((data) => { }) ``` -## ScanMode8+ +## ScanMode8+(deprecated) 枚举,扫描模式。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ScanMode](js-apis-bluetoothManager.md#scanmode)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3313,10 +3367,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | 可连接general发现模式。 | | SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | 可连接limited发现模式。 | -## BondState8+ +## BondState8+(deprecated) 枚举,配对状态。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BondState](js-apis-bluetoothManager.md#bondstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3326,10 +3384,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | BOND_STATE_BONDED | 2 | 已配对。 | -## SppOption8+ +## SppOption8+(deprecated) 描述spp的配置参数。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.SppOption](js-apis-bluetoothManager.md#sppoption)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3339,10 +3401,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | type | [SppType](#spptype) | 是 | 是 | Spp链路类型。 | -## SppType8+ +## SppType8+(deprecated) 枚举,Spp链路类型。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.SppType](js-apis-bluetoothManager.md#spptype)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3350,10 +3416,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | SPP_RFCOMM | 0 | 表示rfcomm链路类型。 | -## GattService +## GattService(deprecated) 描述service的接口参数定义。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.GattService](js-apis-bluetoothManager.md#gattservice)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3364,10 +3434,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | includeServices | Array<[GattService](#gattservice)> | 是 | 是 | 当前服务依赖的其它服务。 | -## BLECharacteristic +## BLECharacteristic(deprecated) 描述characteristic的接口参数定义 。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLECharacteristic](js-apis-bluetoothManager.md#blecharacteristic)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3378,10 +3452,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | descriptors | Array<[BLEDescriptor](#bledescriptor)> | 是 | 是 | 特定特征的描述符列表。 | -## BLEDescriptor +## BLEDescriptor(deprecated) 描述descriptor的接口参数定义 。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLEDescriptor](js-apis-bluetoothManager.md#bledescriptor)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3392,10 +3470,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | descriptorValue | ArrayBuffer | 是 | 是 | 描述符对应的二进制值。 | -## NotifyCharacteristic +## NotifyCharacteristic(deprecated) 描述server端特征值变化时发送的特征通知参数定义。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.NotifyCharacteristic](js-apis-bluetoothManager.md#notifycharacteristic)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3406,10 +3488,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | confirm | boolean | 是 | 是 | 如果是notification则对端回复确认设置为true,如果是indication则对端不需要回复确认设置为false。 | -## CharacteristicReadReq +## CharacteristicReadReq(deprecated) 描述server端订阅后收到的特征值读请求事件参数结构。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.CharacteristicReadRequest](js-apis-bluetoothManager.md#characteristicreadrequest)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3421,10 +3507,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | -## CharacteristicWriteReq +## CharacteristicWriteReq(deprecated) 描述server端订阅后收到的特征值写请求事件参数结构。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.CharacteristicWriteRequest](js-apis-bluetoothManager.md#characteristicwriterequest)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3437,10 +3527,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | -## DescriptorReadReq +## DescriptorReadReq(deprecated) 描述server端订阅后收到的描述符读请求事件参数结构。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.DescriptorReadRequest](js-apis-bluetoothManager.md#descriptorreadrequest)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3453,10 +3547,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | -## DescriptorWriteReq +## DescriptorWriteReq(deprecated) 描述server端订阅后收到的描述符写请求事件参数结构。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.DescriptorWriteRequest](js-apis-bluetoothManager.md#descriptorwriterequest)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3472,10 +3570,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | -## ServerResponse +## ServerResponse(deprecated) 描述server端回复client端读/写请求的响应参数结构。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ServerResponse](js-apis-bluetoothManager.md#serverresponse)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3487,10 +3589,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | value | ArrayBuffer | 是 | 否 | 表示回复响应的二进制数据。 | -## BLEConnectChangedState +## BLEConnectChangedState(deprecated) 描述Gatt profile连接状态 。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BLEConnectChangedState](js-apis-bluetoothManager.md#bleconnectchangedstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3499,10 +3605,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | state | [ProfileConnectionState](#profileconnectionstate) | 是 | 是 | 表示BLE连接状态的枚举。 | -## ProfileConnectionState +## ProfileConnectionState(deprecated) 枚举,蓝牙设备的profile连接状态。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ProfileConnectionState](js-apis-bluetoothManager.md#profileconnectionstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3513,10 +3623,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | STATE_DISCONNECTING | 3 | 表示profile正在断连。 | -## ScanFilter +## ScanFilter(deprecated) 扫描过滤参数。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ScanFilter](js-apis-bluetoothManager.md#scanfilter)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3524,20 +3638,16 @@ let rssi = gattClient.getRssiValue().then((data) => { | deviceId | string | 是 | 是 | 表示过滤的BLE设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | | name | string | 是 | 是 | 表示过滤的BLE设备名。 | | serviceUuid | string | 是 | 是 | 表示过滤包含该UUID服务的设备,例如:00001888-0000-1000-8000-00805f9b34fb。 | -| serviceUuidMask9+ | string | 是 | 是 | 表示过滤包含该UUID服务掩码的设备,例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | -| serviceSolicitationUuid9+ | string | 是 | 是 | 表示过滤包含该UUID服务请求的设备,例如:00001888-0000-1000-8000-00805F9B34FB。 | -| serviceSolicitationUuidMask9+ | string | 是 | 是 | 表示过滤包含该UUID服务请求掩码的设备,例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | -| serviceData9+ | ArrayBuffer | 是 | 是 | 表示过滤包含该服务相关数据的设备,例如:[0x90,0x00,0xF1,0xF2]。 | -| serviceDataMask9+ | ArrayBuffer | 是 | 是 | 表示过滤包含该服务相关数据掩码的设备,例如:[0xFF,0xFF,0xFF,0xFF]。 | -| manufactureId9+ | number | 是 | 是 | 表示过滤包含该制造商ID的设备,例如:0x0006。 | -| manufactureData9+ | ArrayBuffer | 是 | 是 | 表示过滤包含该制造商相关数据的设备,例如:[0x1F,0x2F,0x3F]。 | -| manufactureDataMask9+ | ArrayBuffer | 是 | 是 | 表示过滤包含该制造商相关数据掩码的设备,例如:[0xFF,0xFF,0xFF]。 | -## ScanOptions +## ScanOptions(deprecated) 扫描的配置参数。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ScanOptions](js-apis-bluetoothManager.md#scanoptions)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3547,10 +3657,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | matchMode | [MatchMode](#matchmode) | 是 | 是 | 表示硬件的过滤匹配模式,默认值为MATCH_MODE_AGGRESSIVE。 | -## ScanDuty +## ScanDuty(deprecated) 枚举,扫描模式。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ScanDuty](js-apis-bluetoothManager.md#scanduty)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3560,10 +3674,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | SCAN_MODE_LOW_LATENCY | 2 | 表示低延迟模式。 | -## MatchMode +## MatchMode(deprecated) 枚举,硬件过滤匹配模式。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.MatchMode](js-apis-bluetoothManager.md#matchmode)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3572,10 +3690,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | MATCH_MODE_STICKY | 2 | 表示硬件上报扫描结果门限较高,更高的功率门限以及扫描到多次才会上报。 | -## ScanResult +## ScanResult(deprecated) 扫描结果上报数据。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ScanResult](js-apis-bluetoothManager.md#scanresult)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3585,10 +3707,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | data | ArrayBuffer | 是 | 否 | 表示扫描到的设备发送的广播包。 | -## BluetoothState +## BluetoothState(deprecated) 枚举,蓝牙开关状态。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BluetoothState](js-apis-bluetoothManager.md#bluetoothstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3602,10 +3728,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | STATE_BLE_TURNING_OFF | 6 | 表示蓝牙正在关闭LE-only模式。 | -## AdvertiseSetting +## AdvertiseSetting(deprecated) 描述蓝牙低功耗设备发送广播的参数。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.AdvertiseSetting](js-apis-bluetoothManager.md#advertisesetting)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3615,10 +3745,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | connectable | boolean | 是 | 是 | 表示是否是可连接广播,默认值设置为true。 | -## AdvertiseData +## AdvertiseData(deprecated) 描述BLE广播数据包的内容。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.AdvertiseData](js-apis-bluetoothManager.md#advertisedata)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3628,10 +3762,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceData | Array<[ServiceData](#servicedata)> | 是 | 是 | 表示要广播的服务数据列表。 | -## ManufactureData +## ManufactureData(deprecated) 描述BLE广播数据包的内容。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ManufactureData](js-apis-bluetoothManager.md#manufacturedata)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3640,10 +3778,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | manufactureValue | ArrayBuffer | 是 | 是 | 表示制造商发送的制造商数据。 | -## ServiceData +## ServiceData(deprecated) 描述广播包中服务数据内容。 +> **说明:**
+> 从API version 7开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ServiceData](js-apis-bluetoothManager.md#servicedata)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3652,10 +3794,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | serviceValue | ArrayBuffer | 是 | 是 | 表示服务数据。 | -## PinRequiredParam8+ +## PinRequiredParam8+(deprecated) 描述配对请求参数。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.PinRequiredParam](js-apis-bluetoothManager.md#pinrequiredparam)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3664,10 +3810,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | pinCode | string | 是 | 否 | 表示要配对的密钥。 | -## BondStateParam8+ +## BondStateParam8+(deprecated) 描述配对状态参数。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.BondStateParam](js-apis-bluetoothManager.md#bondstateparam)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3676,10 +3826,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | state | BondState | 是 | 否 | 表示配对设备的状态。 | -## StateChangeParam8+ +## StateChangeParam8+(deprecated) 描述profile状态改变参数。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.StateChangeParam](js-apis-bluetoothManager.md#statechangeparam)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3688,10 +3842,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | state | [ProfileConnectionState](#profileconnectionstate) | 是 | 否 | 表示蓝牙设备的profile连接状态。 | -## DeviceClass8+ +## DeviceClass8+(deprecated) 描述蓝牙设备的类别。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.DeviceClass](js-apis-bluetoothManager.md#deviceclass)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -3702,10 +3860,14 @@ let rssi = gattClient.getRssiValue().then((data) => { -## MajorClass8+ +## MajorClass8+(deprecated) 枚举,蓝牙设备主要类别。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.MajorClass](js-apis-bluetoothManager.md#majorclass)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3723,10 +3885,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | MAJOR_UNCATEGORIZED | 0x1F00 | 表示未分类设备。 | -## MajorMinorClass8+ +## MajorMinorClass8+(deprecated) 枚举,主要次要蓝牙设备类别。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.MajorMinorClass](js-apis-bluetoothManager.md#majorminorclass)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3819,10 +3985,14 @@ let rssi = gattClient.getRssiValue().then((data) => { | HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | 表示个人移动健康设备。 | -## PlayingState8+ +## PlayingState8+(deprecated) 枚举,蓝牙A2DP 播放状态。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.PlayingState](js-apis-bluetoothManager.md#playingstate)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | @@ -3831,15 +4001,17 @@ let rssi = gattClient.getRssiValue().then((data) => { | STATE_PLAYING | 0x0001 | 表示正在播放。 | -## ProfileId8+ +## ProfileId8+(deprecated) 蓝牙profile枚举,API9新增PROFILE_HID_HOST,PROFILE_PAN_NETWORK。 +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[bluetoothManager.ProfileId](js-apis-bluetoothManager.md#profileid)替代。 + **系统能力**:SystemCapability.Communication.Bluetooth.Core。 | 名称 | 值 | 说明 | | -------------------------------- | ------ | --------------- | | PROFILE_A2DP_SOURCE | 1 | 表示A2DP profile。 | -| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | 表示HFP profile。 | -| PROFILE_HID_HOST9+ | 6 | 表示HID profile。 | -| PROFILE_PAN_NETWORK9+ | 7 | 表示PAN profile。 | \ No newline at end of file +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | 表示HFP profile。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md b/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md new file mode 100644 index 0000000000000000000000000000000000000000..1386e7f32ab296447a7930bbfe583d1ac4afb3ec --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md @@ -0,0 +1,4491 @@ +# @ohos.bluetoothManager (蓝牙) + +蓝牙模块提供了基础的传统蓝牙能力以及BLE的扫描、广播等功能。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + + +## 导入模块 + +```js +import bluetoothManager from '@ohos.bluetoothManager'; +``` + + +## bluetoothManager.enableBluetooth + +enableBluetooth(): void + +开启蓝牙。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.enableBluetooth(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.disableBluetooth + +disableBluetooth(): void + +关闭蓝牙。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.disableBluetooth(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getLocalName + +getLocalName(): string + +获取蓝牙本地设备名称。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ------ | --------- | +| string | 蓝牙本地设备名称。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let localName = bluetoothManager.getLocalName(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getState + +getState(): BluetoothState + +获取蓝牙开关状态。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | --------- | +| [BluetoothState](#bluetoothstate) | 表示蓝牙开关状态。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let state = bluetoothManager.getState(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getBtConnectionState + +getBtConnectionState(): ProfileConnectionState + +获取蓝牙设备的Profile连接状态。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | 表示蓝牙设备的Profile连接状态。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let connectionState = bluetoothManager.getBtConnectionState(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setLocalName + +setLocalName(name: string): void + +设置蓝牙本地设备名称。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------------------- | +| name | string | 是 | 要设置的蓝牙名称,最大长度为248字节数。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.setLocalName('device_name'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.pairDevice + +pairDevice(deviceId: string): void + +发起蓝牙配对。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | 是 | 表示配对的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + // 实际的地址可由扫描流程获取 + bluetoothManager.pairDevice("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getProfileConnectionState + +getProfileConnectionState(profileId: ProfileId): ProfileConnectionState + +获取profile的连接状态。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | --------- | ---- | ------------------------------------- | +| ProfileId | profileId | 是 | 表示profile的枚举值,例如:PROFILE_A2DP_SOURCE。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | profile的连接状态。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let result = bluetoothManager.getProfileConnectionState(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.cancelPairedDevice + +cancelPairedDevice(deviceId: string): void + +删除配对的远程设备。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | 是 | 表示要删除的远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.cancelPairedDevice("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getRemoteDeviceName + +getRemoteDeviceName(deviceId: string): string + +获取对端蓝牙设备的名称。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------- | +| string | 以字符串格式返回设备名称。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let remoteDeviceName = bluetoothManager.getRemoteDeviceName("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getRemoteDeviceClass + +getRemoteDeviceClass(deviceId: string): DeviceClass + +获取对端蓝牙设备的类别。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | -------- | +| [DeviceClass](#deviceclass) | 远程设备的类别。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let remoteDeviceClass = bluetoothManager.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getPairedDevices + +getPairedDevices(): Array<string> + +获取蓝牙配对列表。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------- | +| Array<string> | 已配对蓝牙设备的地址列表。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let devices = bluetoothManager.getPairedDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setBluetoothScanMode + +setBluetoothScanMode(mode: ScanMode, duration: number): void + +设置蓝牙扫描模式,可以被远端设备发现。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ---------------------------- | +| mode | [ScanMode](#scanmode) | 是 | 蓝牙扫描模式。 | +| duration | number | 是 | 设备可被发现的持续时间,单位为毫秒;设置为0则持续可发现。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + // 设置为可连接可发现才可被远端设备扫描到,可以连接。 + bluetoothManager.setBluetoothScanMode(bluetoothManager.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getBluetoothScanMode + +getBluetoothScanMode(): ScanMode + +获取蓝牙扫描模式。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------- | +| [ScanMode](#scanmode) | 蓝牙扫描模式。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let scanMode = bluetoothManager.getBluetoothScanMode(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.startBluetoothDiscovery + +startBluetoothDiscovery(): void + +开启蓝牙扫描,可以发现远端设备。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH 和 ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +let deviceId; +function onReceiveEvent(data) { + deviceId = data; +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); + bluetoothManager.startBluetoothDiscovery(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.stopBluetoothDiscovery + +stopBluetoothDiscovery(): void + +关闭蓝牙扫描。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.stopBluetoothDiscovery(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setDevicePairingConfirmation + +setDevicePairingConfirmation(device: string, accept: boolean): void + +设置设备配对请求确认。 + +**需要权限**:ohos.permission.MANAGE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | -------------------------------- | +| device | string | 是 | 表示远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| accept | boolean | 是 | 接受配对请求设置为true,否则设置为false。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js + +try { + // 订阅“pinRequired”配对请求事件,收到远端配对请求后设置配对确认 + function onReceivePinRequiredEvent(data) { // data为配对请求的入参,配对请求参数 + console.info('pin required = '+ JSON.stringify(data)); + bluetoothManager.setDevicePairingConfirmation(data.deviceId, true); + } + bluetoothManager.on("pinRequired", onReceivePinRequiredEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('bluetoothDeviceFind') + +on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void + +订阅蓝牙设备发现上报事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | -------------------------------------- | +| type | string | 是 | 填写"bluetoothDeviceFind"字符串,表示蓝牙设备发现事件。 | +| callback | Callback<Array<string>> | 是 | 表示回调函数的入参,发现的设备集合。回调函数由用户创建通过该接口注册。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { // data为蓝牙设备地址集合 + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('bluetoothDeviceFind') + +off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void + +取消订阅蓝牙设备发现上报事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"bluetoothDeviceFind"字符串,表示蓝牙设备发现事件。 | +| callback | Callback<Array<string>> | 否 | 表示取消订阅蓝牙设备发现事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); + bluetoothManager.off('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('pinRequired') + +on(type: "pinRequired", callback: Callback<PinRequiredParam>): void + +订阅远端蓝牙设备的配对请求事件。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| type | string | 是 | 填写"pinRequired"字符串,表示配对请求事件。 | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | 是 | 表示回调函数的入参,配对请求。回调函数由用户创建通过该接口注册。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { // data为配对请求参数 + console.info('pin required = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('pinRequired', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('pinRequired') + +off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void + +取消订阅远端蓝牙设备的配对请求事件。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"pinRequired"字符串,表示配对请求事件。 | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | 否 | 表示取消订阅蓝牙配对请求事件上报,入参为配对请求参数。不填该参数则取消订阅该type对应的所有回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('pin required = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('pinRequired', onReceiveEvent); + bluetoothManager.off('pinRequired', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('bondStateChange') + +on(type: "bondStateChange", callback: Callback<BondStateParam>): void + +订阅蓝牙配对状态改变事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| type | string | 是 | 填写"bondStateChange"字符串,表示蓝牙配对状态改变事件。 | +| callback | Callback<[BondStateParam](#BondStateParam)> | 是 | 表示回调函数的入参,配对的状态。回调函数由用户创建通过该接口注册。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { // data为回调函数入参,表示配对的状态 + console.info('pair state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bondStateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('bondStateChange') + +off(type: "bondStateChange", callback?: Callback<BondStateParam>): void + +取消订阅蓝牙配对状态改变事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"bondStateChange"字符串,表示蓝牙配对状态改变事件。 | +| callback | Callback<[BondStateParam](#BondStateParam)> | 否 | 表示取消订阅蓝牙配对状态改变事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bond state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bondStateChange', onReceiveEvent); + bluetoothManager.off('bondStateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('stateChange') + +on(type: "stateChange", callback: Callback<BluetoothState>): void + +订阅蓝牙连接状态改变事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| type | string | 是 | 填写"stateChange"字符串,表示蓝牙状态改变事件。 | +| callback | Callback<[BluetoothState](#bluetoothstate)> | 是 | 表示回调函数的入参,蓝牙状态。回调函数由用户创建通过该接口注册。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('stateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('stateChange') + +off(type: "stateChange", callback?: Callback<BluetoothState>): void + +取消订阅蓝牙连接状态改变事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"stateChange"字符串,表示蓝牙状态改变事件。 | +| callback | Callback<[BluetoothState](#bluetoothstate)> | 否 | 表示取消订阅蓝牙状态改变事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('stateChange', onReceiveEvent); + bluetoothManager.off('stateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppListen + +sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void + +创建一个服务端监听Socket。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ----------------------- | +| name | string | 是 | 服务的名称。 | +| option | [SppOption](#sppoption) | 是 | spp监听配置参数。 | +| callback | AsyncCallback<number> | 是 | 表示回调函数的入参,服务端Socket的id。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} + +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + bluetoothManager.sppListen('server1', sppOption, serverSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppAccept + +sppAccept(serverSocket: number, callback: AsyncCallback<number>): void + +服务端监听socket等待客户端连接。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | --------------------------- | ---- | ----------------------- | +| serverSocket | number | 是 | 服务端socket的id。 | +| callback | AsyncCallback<number> | 是 | 表示回调函数的入参,客户端socket的id。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +let clientNumber = -1; +function acceptClientSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth clientSocket Number: ' + number); + // 获取的clientNumber用作服务端后续读/写操作socket的id。 + clientNumber = number; + } +} +try { + bluetoothManager.sppAccept(serverNumber, acceptClientSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppConnect + +sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void + +客户端向远端设备发起spp连接。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------ | +| device | string | 是 | 对端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| option | [SppOption](#sppoption) | 是 | spp客户端连接配置参数。 | +| callback | AsyncCallback<number> | 是 | 表示回调函数的入参,客户端socket的id。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js + +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // 获取的clientNumber用作客户端后续读/写操作socket的id。 + clientNumber = number; +} +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + bluetoothManager.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppCloseServerSocket + +sppCloseServerSocket(socket: number): void + +关闭服务端监听Socket,入参socket由sppListen接口返回。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------- | +| socket | number | 是 | 服务端监听socket的id。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +try { + bluetoothManager.sppCloseServerSocket(serverNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppCloseClientSocket + +sppCloseClientSocket(socket: number): void + +关闭客户端socket,入参socket由sppAccept或sppConnect接口获取。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------- | +| 参数名 | 类型 | 必填 | 说明 | +| socket | number | 是 | 客户端socket的id。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // 获取的clientNumber用作客户端后续读/写操作socket的id。 + clientNumber = number; +} +try { + bluetoothManager.sppCloseClientSocket(clientNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppWrite + +sppWrite(clientSocket: number, data: ArrayBuffer): void + +通过socket向远端发送数据,入参clientSocket由sppAccept或sppConnect接口获取 。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ----------- | ---- | ------------- | +| clientSocket | number | 是 | 客户端socket的id。 | +| data | ArrayBuffer | 是 | 写入的数据。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**示例:** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // 获取的clientNumber用作客户端后续读/写操作socket的id。 + clientNumber = number; +} +let arrayBuffer = new ArrayBuffer(8); +let data = new Uint8Array(arrayBuffer); +data[0] = 123; +try { + bluetoothManager.sppWrite(clientNumber, arrayBuffer); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('sppRead') + +on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void + +订阅spp读请求事件,入参clientSocket由sppAccept或sppConnect接口获取。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | --------------------------- | ---- | -------------------------- | +| type | string | 是 | 填写"sppRead"字符串,表示spp读请求事件。 | +| clientSocket | number | 是 | 客户端socket的id。 | +| callback | Callback<ArrayBuffer> | 是 | 表示回调函数的入参,读取到的数据。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**示例:** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // 获取的clientNumber用作客户端后续读/写操作socket的id。 + clientNumber = number; +} +function dataRead(dataBuffer) { + let data = new Uint8Array(dataBuffer); + console.log('bluetooth data is: ' + data[0]); +} +try { + bluetoothManager.on('sppRead', clientNumber, dataRead); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('sppRead') + +off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void + +取消订阅spp读请求事件,入参clientSocket由sppAccept或sppConnect接口获取。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | --------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"sppRead"字符串,表示spp读请求事件。 | +| clientSocket | number | 是 | 客户端Socket的id。 | +| callback | Callback<ArrayBuffer> | 否 | 表示取消订阅spp读请求事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // 获取的clientNumber用作客户端后续读/写操作socket的id。 + clientNumber = number; +} +try { + bluetoothManager.off('sppRead', clientNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## bluetoothManager.getProfileInstance + +getProfileInstance(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile + +通过ProfileId,获取profile的对象实例,API9新增了HidHostProfile,PanProfile。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | --------- | ---- | ------------------------------------- | +| profileId | [ProfileId](#ProfileId) | 是 | 表示profile的枚举值,例如:PROFILE_A2DP_SOURCE。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [A2dpSourceProfile](#a2dpsourceprofile)或 [HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile)或[HidHostProfile](#hidhostprofile)或[PanProfile](#panprofile) | 对应的profile的对象实例,当前支持A2dpSourceProfile/HandsFreeAudioGatewayProfile/HidHostProfile/PanProfile。 | + +**示例:** + +```js +try { + let hidHost = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HID_HOST); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.BLE + +### bluetoothManager.BLE.createGattServer + +createGattServer(): GattServer + +创建一个可使用的GattServer实例。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------------------------ | +| [GattServer](#gattserver) | server端类,使用server端方法之前需要创建该类的实例进行操作。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +``` + + +### bluetoothManager.BLE.createGattClientDevice + +createGattClientDevice(deviceId: string): GattClientDevice + +创建一个可使用的GattClientDevice实例。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------ | +| deviceId | string | 是 | 对端设备地址, 例如:"XX:XX:XX:XX:XX:XX"。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------ | +| [GattClientDevice](#gattclientdevice) | client端类,使用client端方法之前需要创建该类的实例进行操作。 | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.getConnectedBLEDevices + +getConnectedBLEDevices(): Array<string> + +获取和当前设备连接的BLE设备。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------- | +| Array<string> | 返回当前设备作为Server端时连接BLE设备地址集合。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let result = bluetoothManager.BLE.getConnectedBLEDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.startBLEScan + +startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void + +发起BLE扫描流程。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH 和 ohos.permission.MANAGE_BLUETOOTH 和 ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------------------------- | ---- | ----------------------------------- | +| filters | Array<[ScanFilter](#scanfilter)> | 是 | 表示扫描结果过滤策略集合,如果不使用过滤的方式,该参数设置为null。 | +| options | [ScanOptions](#scanoptions) | 否 | 表示扫描的参数配置,可选参数。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('BLE scan device find result = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on("BLEDeviceFind", onReceiveEvent); + bluetoothManager.BLE.startBLEScan( + [{ + deviceId:"XX:XX:XX:XX:XX:XX", + name:"test", + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" + }], + { + interval: 500, + dutyMode: bluetoothManager.ScanDuty.SCAN_MODE_LOW_POWER, + matchMode: bluetoothManager.MatchMode.MATCH_MODE_AGGRESSIVE, + } + ); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.stopBLEScan + +stopBLEScan(): void + +停止BLE扫描流程。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + bluetoothManager.BLE.stopBLEScan(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.on('BLEDeviceFind') + +on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void + +订阅BLE设备发现上报事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| type | string | 是 | 填写"BLEDeviceFind"字符串,表示BLE设备发现事件。 | +| callback | Callback<Array<[ScanResult](#scanresult)>> | 是 | 表示回调函数的入参,发现的设备集合。回调函数由用户创建通过该接口注册。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.off('BLEDeviceFind') + +off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void + +取消订阅BLE设备发现上报事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"BLEDeviceFind"字符串,表示BLE设备发现事件。 | +| callback | Callback<Array<[ScanResult](#scanresult)>> | 否 | 表示取消订阅BLE设备发现事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on('BLEDeviceFind', onReceiveEvent); + bluetoothManager.BLE.off('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## BaseProfile + +profile基类。 + + +### getConnectionDevices + +getConnectionDevices(): Array<string> + +获取已连接设备列表。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------- | +| Array<string> | 返回已连接设备的地址列表。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let retArray = a2dpSrc.getConnectionDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +### getDeviceState + +getDeviceState(device: string): ProfileConnectionState + +获取设备profile的连接状态。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------- | ----------------------- | +| [ProfileConnectionState](#profileconnectionstate) | 返回profile的连接状态。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## A2dpSourceProfile + +使用A2dpSourceProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 + + +### connect + +connect(device: string): void + +发起设备的A2dp服务连接请求。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +断开设备的a2dp服务连接。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +订阅a2dp连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | + +**返回值:** + +无 + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); +} +let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; +a2dpSrc.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +取消订阅a2dp连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | + +**返回值:** + +无 + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); +} +let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; +a2dpSrc.on('connectionStateChange', onReceiveEvent); +a2dpSrc.off('connectionStateChange', onReceiveEvent); +``` + + +### getPlayingState + +getPlayingState(device: string): PlayingState + +获取设备的播放状态。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | ---------- | +| [PlayingState](#PlayingState) | 远端设备的播放状态。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## HandsFreeAudioGatewayProfile + +使用HandsFreeAudioGatewayProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 + + +### connect + +connect(device: string): void + +连接设备的HFP服务。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as bluetoothManager.HandsFreeAudioGatewayProfile; + hfpAg.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +断开连接设备的HFP服务。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as bluetoothManager.HandsFreeAudioGatewayProfile; + hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +订阅HFP连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('hfp state = '+ JSON.stringify(data)); +} +let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetoothManager.HandsFreeAudioGatewayProfile; +hfpAg.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +取消订阅HFP连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('hfp state = '+ JSON.stringify(data)); +} +let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetoothManager.HandsFreeAudioGatewayProfile; +hfpAg.on('connectionStateChange', onReceiveEvent); +hfpAg.off('connectionStateChange', onReceiveEvent); +``` + + +## HidHostProfile + +使用HidHostProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 + + +### connect + +connect(device: string): void + +连接设备的HidHost服务。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let hidHostProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; + hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +断开连接设备的HidHost服务。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let hidHostProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; + hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +订阅HidHost连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('hidHost state = '+ JSON.stringify(data)); +} +let hidHost = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; +hidHost.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +取消订阅HidHost连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('hidHost state = '+ JSON.stringify(data)); +} +let hidHost = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; +hidHost.on('connectionStateChange', onReceiveEvent); +hidHost.off('connectionStateChange', onReceiveEvent); +``` + + +## PanProfile + +使用PanProfile方法之前需要创建该类的实例进行操作,通过getProfile()方法构造此实例。 + + +### disconnect + +disconnect(device: string): void + +断开连接设备的Pan服务。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| device | string | 是 | 远端设备地址。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + panProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +订阅Pan连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 是 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; +panProfile.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +取消订阅Pan连接状态变化事件。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | string | 是 | 填写"connectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | 否 | 表示回调函数的入参。 | + +**示例:** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; +panProfile.on('connectionStateChange', onReceiveEvent); +panProfile.off('connectionStateChange', onReceiveEvent); +``` + + +### setTethering + +setTethering(enable: boolean): void + +设置网络共享状态。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| value | boolean | 是 | 是否设置蓝牙共享。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + panProfile.setTethering(true); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### isTetheringOn + +isTetheringOn(): boolean + +获取网络共享状态。 + +**系统接口**:此接口为系统接口。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------------------- | +| boolean | 网络共享开启返回true,网络共享关闭返回false。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + let ret = panProfile.isTetheringOn(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## GattServer + +server端类,使用server端方法之前需要创建该类的实例进行操作,通过createGattServer()方法构造此实例。 + + +### startAdvertising + +startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void + +开始发送BLE广播。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------------------------------------- | ---- | -------------- | +| setting | [AdvertiseSetting](#advertisesetting) | 是 | BLE广播的相关参数。 | +| advData | [AdvertiseData](#advertisedata) | 是 | BLE广播包内容。 | +| advResponse | [AdvertiseData](#advertisedata) | 否 | BLE回复扫描请求回复响应。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +let manufactureValueBuffer = new Uint8Array(4); +manufactureValueBuffer[0] = 1; +manufactureValueBuffer[1] = 2; +manufactureValueBuffer[2] = 3; +manufactureValueBuffer[3] = 4; + +let serviceValueBuffer = new Uint8Array(4); +serviceValueBuffer[0] = 4; +serviceValueBuffer[1] = 6; +serviceValueBuffer[2] = 7; +serviceValueBuffer[3] = 8; +console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); +console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.startAdvertising({ + interval:150, + txPower:60, + connectable:true, + },{ + serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:4567, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + },{ + serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:1789, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001889-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + }); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### stopAdvertising + +stopAdvertising(): void + +停止发送BLE广播。 + +**需要权限**:ohos.permission.DISCOVER_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.stopAdvertising(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### addService + +addService(service: GattService): void + +server端添加服务。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------- | ---- | ------------------------ | +| service | [GattService](#gattservice) | 是 | 服务端的service数据。BLE广播的相关参数 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +// 创建descriptors +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; + +// 创建characteristics +let characteristics = []; +let arrayBufferC = new ArrayBuffer(8); +let cccV = new Uint8Array(arrayBufferC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +characteristics[0] = characteristic; + +// 创建gattService +let gattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]}; + +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.addService(gattService); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### removeService + +removeService(serviceUuid: string): void + +删除已添加的服务。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------------------------------------- | +| serviceUuid | string | 是 | service的UUID,例如“00001810-0000-1000-8000-00805F9B34FB”。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**示例:** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.removeService('00001810-0000-1000-8000-00805F9B34FB'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### close + +close(): void + +关闭服务端功能,去注册server在协议栈的注册,调用该接口后[GattServer](#gattserver)实例将不能再使用。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.close(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### notifyCharacteristicChanged + +notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): void + +server端特征值发生变化时,主动通知已连接的client设备。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | +| deviceId | string | 是 | 接收通知的client端设备地址,例如“XX:XX:XX:XX:XX:XX”。 | +| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | 是 | 通知的特征值数据。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +// 创建descriptors +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false}; +let server = bluetoothManager.BLE.createGattServer(); +try { + server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### sendResponse + +sendResponse(serverResponse: ServerResponse): void + +server端回复client端的读写请求。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------------- | ---- | --------------- | +| serverResponse | [ServerResponse](#serverresponse) | 是 | server端回复的响应数据。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +/* send response */ +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +let serverResponse = { + "deviceId": "XX:XX:XX:XX:XX:XX", + "transId": 0, + "status": 0, + "offset": 0, + "value": arrayBufferCCC, +}; + +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.sendResponse(serverResponse); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('characteristicRead') + +on(type: "characteristicRead", callback: Callback<CharacteristicReadRequest>): void + +server端订阅特征值读请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------------- | +| type | string | 是 | 填写"characteristicRead"字符串,表示特征值读请求事件。 | +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | 是 | 表示回调函数的入参,client端发送的读请求数据。 | + +**示例:** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +function ReadCharacteristicReq(CharacteristicReadRequest) { + let deviceId = CharacteristicReadRequest.deviceId; + let transId = CharacteristicReadRequest.transId; + let offset = CharacteristicReadRequest.offset; + let characteristicUuid = CharacteristicReadRequest.characteristicUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("characteristicRead", ReadCharacteristicReq); +``` + + +### off('characteristicRead') + +off(type: "characteristicRead", callback?: Callback<CharacteristicReadRequest>): void + +server端取消订阅特征值读请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"characteristicRead"字符串,表示特征值读请求事件。 | +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | 否 | 表示取消订阅特征值读请求事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("characteristicRead"); +``` + + +### on('characteristicWrite') + +on(type: "characteristicWrite", callback: Callback<CharacteristicWriteRequest>): void + +server端订阅特征值写请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | -------------------------------------- | +| type | string | 是 | 填写"characteristicWrite"字符串,表示特征值写请求事件。 | +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | 是 | 表示回调函数的入参,client端发送的写请求数据。 | + +**示例:** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +function WriteCharacteristicReq(CharacteristicWriteRequest) { + let deviceId = CharacteristicWriteRequest.deviceId; + let transId = CharacteristicWriteRequest.transId; + let offset = CharacteristicWriteRequest.offset; + let isPrep = CharacteristicWriteRequest.isPrep; + let needRsp = CharacteristicWriteRequest.needRsp; + let value = new Uint8Array(CharacteristicWriteRequest.value); + let characteristicUuid = CharacteristicWriteRequest.characteristicUuid; + + cccValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("characteristicWrite", WriteCharacteristicReq); +``` + + +### off('characteristicWrite') + +off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteRequest>): void + +server端取消订阅特征值写请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"characteristicWrite"字符串,表示特征值写请求事件。 | +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | 否 | 表示取消订阅特征值写请求事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("characteristicWrite"); +``` + + +### on('descriptorRead') + +on(type: "descriptorRead", callback: Callback<DescriptorReadRequest>): void + +server端订阅描述符读请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------------------------------- | +| type | string | 是 | 填写"descriptorRead"字符串,表示描述符读请求事件。 | +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | 是 | 表示回调函数的入参,client端发送的读请求数据。 | + +**示例:** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +descValue[0] = 1101; +function ReadDescriptorReq(DescriptorReadRequest) { + let deviceId = DescriptorReadRequest.deviceId; + let transId = DescriptorReadRequest.transId; + let offset = DescriptorReadRequest.offset; + let descriptorUuid = DescriptorReadRequest.descriptorUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("descriptorRead", ReadDescriptorReq); +``` + + +### off('descriptorRead') + +off(type: "descriptorRead", callback?: Callback<DescriptorReadRequest>): void + +server端取消订阅描述符读请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"descriptorRead"字符串,表示描述符读请求事件。 | +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | 否 | 表示取消订阅描述符读请求事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("descriptorRead"); +``` + + +### on('descriptorWrite') + +on(type: "descriptorWrite", callback: Callback<DescriptorWriteRequest>): void + +server端订阅描述符写请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------- | +| type | string | 是 | 填写"descriptorWrite"字符串,表示描述符写请求事件。 | +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | 是 | 表示回调函数的入参,client端发送的写请求数据。 | + +**示例:** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +function WriteDescriptorReq(DescriptorWriteRequest) { + let deviceId = DescriptorWriteRequest.deviceId; + let transId = DescriptorWriteRequest.transId; + let offset = DescriptorWriteRequest.offset; + let isPrep = DescriptorWriteRequest.isPrep; + let needRsp = DescriptorWriteRequest.needRsp; + let value = new Uint8Array(DescriptorWriteRequest.value); + let descriptorUuid = DescriptorWriteRequest.descriptorUuid; + + descValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("descriptorRead", WriteDescriptorReq); +``` + + +### off('descriptorWrite') + +off(type: "descriptorWrite", callback?: Callback<DescriptorWriteRequest>): void + +server端取消订阅描述符写请求事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"descriptorWrite"字符串,表示描述符写请求事件。 | +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | 否 | 表示取消订阅描述符写请求事件上报。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("descriptorWrite"); +``` + + +### on('connectStateChange') + +on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void + +server端订阅BLE连接状态变化事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectStateChange"字符串,表示BLE连接状态变化事件。 | +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | 是 | 表示回调函数的入参,连接状态。 | + +**示例:** + +```js +function Connected(BLEConnectChangedState) { + let deviceId = BLEConnectChangedState.deviceId; + let status = BLEConnectChangedState.state; +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("connectStateChange", Connected); +``` + + +### off('connectStateChange') + +off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void + +server端取消订阅BLE连接状态变化事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"connectStateChange"字符串,表示BLE连接状态变化事件。 | +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | 否 | 表示取消订阅BLE连接状态变化事件。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("connectStateChange"); +``` + + +## GattClientDevice + +client端类,使用client端方法之前需要创建该类的实例进行操作,通过createGattClientDevice(deviceId: string)方法构造此实例。 + + +### connect + +connect(): void + +client端发起连接远端蓝牙低功耗设备。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(): void + +client端断开与远端蓝牙低功耗设备的连接。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.disconnect(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### close + +close(): void + +关闭客户端功能,注销client在协议栈的注册,调用该接口后[GattClientDevice](#gattclientdevice)实例将不能再使用。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.close(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + + + +### getServices + +getServices(callback: AsyncCallback<Array<GattService>>): void + +client端获取蓝牙低功耗设备的所有服务,即服务发现 。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<Array<[GattService](#gattservice)>> | 是 | client进行服务发现,通过注册回调函数获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +// callkback 模式 +function getServices(code, gattServices) { + if (code.code == 0) { + let services = gattServices; + console.log('bluetooth code is ' + code.code); + console.log("bluetooth services size is ", services.length); + + for (let i = 0; i < services.length; i++) { + console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); + } + } +} + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices(getServices); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getServices + +getServices(): Promise<Array<GattService>> + +client端获取蓝牙低功耗设备的所有服务,即服务发现。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | --------------------------- | +| Promise<Array<[GattService](#gattservice)>> | client进行服务发现,通过promise形式获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +// Promise 模式 +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices().then(result => { + console.info("getServices successfully:" + JSON.stringify(result)); + }); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void + +client端读取蓝牙低功耗设备特定服务的特征值。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ---------------------------------------- | ---- | ----------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 待读取的特征值。 | +| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | 是 | client读取特征值,通过注册回调函数获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +function readCcc(code, BLECharacteristic) { + if (code.code != 0) { + return; + } + console.log('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); + let value = new Uint8Array(BLECharacteristic.characteristicValue); + console.log('bluetooth characteristic value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic, readCcc); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> + +client端读取蓝牙低功耗设备特定服务的特征值。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------------------- | ---- | -------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 待读取的特征值。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | -------------------------- | +| Promise<[BLECharacteristic](#blecharacteristic)> | client读取特征值,通过promise形式获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void + +client端读取蓝牙低功耗设备特定的特征包含的描述符。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------- | ---- | ----------------------- | +| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 待读取的描述符。 | +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | 是 | client读取描述符,通过注册回调函数获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +function readDesc(code, BLEDescriptor) { + if (code.code != 0) { + return; + } + console.log('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); + let value = new Uint8Array(BLEDescriptor.descriptorValue); + console.log('bluetooth descriptor value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor, readDesc); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> + +client端读取蓝牙低功耗设备特定的特征包含的描述符。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------- | ---- | -------- | +| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 待读取的描述符。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | -------------------------- | +| Promise<[BLEDescriptor](#bledescriptor)> | client读取描述符,通过promise形式获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### writeCharacteristicValue + +writeCharacteristicValue(characteristic: BLECharacteristic): void + +client端向低功耗蓝牙设备写入特定的特征值。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------------------- | ---- | ------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 蓝牙设备特征对应的二进制值及其它参数。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + characteristicValue: bufferCCC, descriptors:descriptors}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeCharacteristicValue(characteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### writeDescriptorValue + +writeDescriptorValue(descriptor: BLEDescriptor): void + +client端向低功耗蓝牙设备特定的描述符写入二进制数据。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------- | ---- | ------------------ | +| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 蓝牙设备描述符的二进制值及其它参数。 | +| boolean | 写描述符操作成功返回true,操作失败返回false。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden。 | +|2900099 | Operation failed. | + +**示例:** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 22; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeDescriptorValue(descriptor); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### setBLEMtuSize + +setBLEMtuSize(mtu: number): void + +client协商远端蓝牙低功耗设备的最大传输单元(Maximum Transmission Unit, MTU),调用[connect](#connect)接口连接成功后才能使用。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | -------------- | +| mtu | number | 是 | 设置范围为22~512字节。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setBLEMtuSize(128); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### setNotifyCharacteristicChanged + +setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): void + +向服务端发送设置通知此特征值请求。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 蓝牙低功耗特征。 | +| enable | boolean | 是 | 启用接收notify设置为true,否则设置为false。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +// 创建descriptors +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setNotifyCharacteristicChanged(characteristic, false); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} + +``` + + +### on('BLECharacteristicChange') + +on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void + +订阅蓝牙低功耗设备的特征值变化事件。需要先调用setNotifyCharacteristicChanged接口才能接收server端的通知。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"BLECharacteristicChange"字符串,表示特征值变化事件。 | +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | 是 | 表示蓝牙低功耗设备的特征值变化事件的回调函数。 | + +**示例:** + +```js +function CharacteristicChange(CharacteristicChangeReq) { + let serviceUuid = CharacteristicChangeReq.serviceUuid; + let characteristicUuid = CharacteristicChangeReq.characteristicUuid; + let value = new Uint8Array(CharacteristicChangeReq.characteristicValue); +} +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLECharacteristicChange', CharacteristicChange); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### off('BLECharacteristicChange') + +off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void + +取消订阅蓝牙低功耗设备的特征值变化事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"BLECharacteristicChange"字符串,表示特征值变化事件。 | +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | 否 | 表示取消订阅蓝牙低功耗设备的特征值变化事件。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLECharacteristicChange'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('BLEConnectionStateChange') + +on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void + +client端订阅蓝牙低功耗设备的连接状态变化事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"BLEConnectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | 是 | 表示连接状态,已连接或断开。 | + +**示例:** + +```js +function ConnectStateChanged(state) { + console.log('bluetooth connect state changed'); + let connectState = state.state; +} +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLEConnectionStateChange', ConnectStateChanged); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### off('BLEConnectionStateChange') + +off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void + +取消订阅蓝牙低功耗设备的连接状态变化事件。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 填写"BLEConnectionStateChange"字符串,表示连接状态变化事件。 | +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | 否 | 表示取消订阅蓝牙低功耗设备的连接状态变化事件。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLEConnectionStateChange'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getDeviceName + +getDeviceName(callback: AsyncCallback<string>): void + +client获取远端蓝牙低功耗设备名。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<string> | 是 | client获取对端server设备名,通过注册回调函数获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +// callback +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName((err, data)=> { + console.info('device name err ' + JSON.stringify(err)); + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getDeviceName + +getDeviceName(): Promise<string> + +client获取远端蓝牙低功耗设备名。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ---------------------------------- | +| Promise<string> | client获取对端server设备名,通过promise形式获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**示例:** + +```js +// promise +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName().then((data) => { + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getRssiValue + +getRssiValue(callback: AsyncCallback<number>): void + +client获取远端蓝牙低功耗设备的信号强度 (Received Signal Strength Indication, RSSI),调用[connect](#connect)接口连接成功后才能使用。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<number> | 是 | 返回信号强度,单位 dBm,通过注册回调函数获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +// callback +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let rssi = gattClient.getRssiValue((err, data)=> { + console.info('rssi err ' + JSON.stringify(err)); + console.info('rssi value' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getRssiValue + +getRssiValue(): Promise<number> + +client获取远端蓝牙低功耗设备的信号强度 (Received Signal Strength Indication, RSSI),调用[connect](#connect)接口连接成功后才能使用。 + +**需要权限**:ohos.permission.USE_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------------------- | +| Promise<number> | 返回信号强度,单位 dBm,通过promise形式获取。 | + +**错误码**: + +以下错误码的详细介绍请参见[蓝牙服务子系统错误码](../errorcodes/errorcode-bluetoothManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**示例:** + +```js +// promise +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + let rssi = gattClient.getRssiValue().then((data) => { + console.info('rssi' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## ScanMode + +枚举,扫描模式。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ---------------------------------------- | ---- | --------------- | +| SCAN_MODE_NONE | 0 | 没有扫描模式。 | +| SCAN_MODE_CONNECTABLE | 1 | 可连接扫描模式。 | +| SCAN_MODE_GENERAL_DISCOVERABLE | 2 | general发现模式。 | +| SCAN_MODE_LIMITED_DISCOVERABLE | 3 | limited发现模式。 | +| SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | 可连接general发现模式。 | +| SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | 可连接limited发现模式。 | + +## BondState + +枚举,配对状态。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ------------------ | ---- | ------ | +| BOND_STATE_INVALID | 0 | 无效的配对。 | +| BOND_STATE_BONDING | 1 | 正在配对。 | +| BOND_STATE_BONDED | 2 | 已配对。 | + + +## SppOption + +描述spp的配置参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------------------- | ---- | ---- | ----------- | +| uuid | string | 是 | 是 | spp单据的uuid。 | +| secure | boolean | 是 | 是 | 是否是安全通道。 | +| type | [SppType](#spptype) | 是 | 是 | Spp链路类型。 | + + +## SppType + +枚举,Spp链路类型。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ---------- | ---- | ------------- | +| SPP_RFCOMM | 0 | 表示rfcomm链路类型。 | + + +## GattService + +描述service的接口参数定义。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | 是 | 是 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | +| isPrimary | boolean | 是 | 是 | 如果是主服务设置为true,否则设置为false。 | +| characteristics | Array<[BLECharacteristic](#blecharacteristic)> | 是 | 是 | 当前服务包含的特征列表。 | +| includeServices | Array<[GattService](#gattservice)> | 是 | 是 | 当前服务依赖的其它服务。 | + + +## BLECharacteristic + +描述characteristic的接口参数定义 。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | 是 | 是 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 是 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| characteristicValue | ArrayBuffer | 是 | 是 | 特征对应的二进制值。 | +| descriptors | Array<[BLEDescriptor](#bledescriptor)> | 是 | 是 | 特定特征的描述符列表。 | + + +## BLEDescriptor + +描述descriptor的接口参数定义 。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | 是 | 是 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 是 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| descriptorUuid | string | 是 | 是 | 描述符(descriptor)的UUID,例如:00002902-0000-1000-8000-00805f9b34fb。 | +| descriptorValue | ArrayBuffer | 是 | 是 | 描述符对应的二进制值。 | + + +## NotifyCharacteristic + +描述server端特征值变化时发送的特征通知参数定义。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------- | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | 是 | 是 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 是 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| characteristicValue | ArrayBuffer | 是 | 是 | 特征对应的二进制值。 | +| confirm | boolean | 是 | 是 | 如果是notification则对端回复确认设置为true,如果是indication则对端不需要回复确认设置为false。 | + + +## CharacteristicReadRequest + +描述server端订阅后收到的特征值读请求事件参数结构。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | 是 | 否 | 表示发送特征值读请求的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| transId | number | 是 | 否 | 表示读请求的传输ID,server端回复响应时需填写相同的传输ID。 | +| offset | number | 是 | 否 | 表示读特征值数据的起始位置。例如:k表示从第k个字节开始读,server端回复响应时需填写相同的offset。 | +| characteristicUuid | string | 是 | 否 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | + + +## CharacteristicWriteRequest + +描述server端订阅后收到的特征值写请求事件参数结构。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | 是 | 否 | 表示发送特征值写请求的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| transId | number | 是 | 否 | 表示写请求的传输ID,server端回复响应时需填写相同的传输ID。 | +| offset | number | 是 | 否 | 表示写特征值数据的起始位置。例如:k表示从第k个字节开始写,server端回复响应时需填写相同的offset。 | +| descriptorUuid | string | 是 | 否 | 表示描述符(descriptor)的UUID,例如:00002902-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 否 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | + + +## DescriptorReadRequest + +描述server端订阅后收到的描述符读请求事件参数结构。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | 是 | 否 | 表示发送描述符读请求的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| transId | number | 是 | 否 | 表示读请求的传输ID,server端回复响应时需填写相同的传输ID。 | +| offset | number | 是 | 否 | 表示读描述符数据的起始位置。例如:k表示从第k个字节开始读,server端回复响应时需填写相同的offset。 | +| descriptorUuid | string | 是 | 否 | 表示描述符(descriptor)的UUID,例如:00002902-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 否 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | + + +## DescriptorWriteRequest + +描述server端订阅后收到的描述符写请求事件参数结构。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| deviceId | string | 是 | 否 | 表示发送描述符写请求的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| transId | number | 是 | 否 | 表示写请求的传输ID,server端回复响应时需填写相同的传输ID。 | +| offset | number | 是 | 否 | 表示写描述符数据的起始位置。例如:k表示从第k个字节开始写,server端回复响应时需填写相同的offset。 | +| isPrep | boolean | 是 | 否 | 表示写请求是否立即执行。 | +| needRsp | boolean | 是 | 否 | 表示是否要给client端回复响应。 | +| value | ArrayBuffer | 是 | 否 | 表示写入的描述符二进制数据。 | +| descriptorUuid | string | 是 | 否 | 表示描述符(descriptor)的UUID,例如:00002902-0000-1000-8000-00805f9b34fb。 | +| characteristicUuid | string | 是 | 否 | 特定特征(characteristic)的UUID,例如:00002a11-0000-1000-8000-00805f9b34fb。 | +| serviceUuid | string | 是 | 否 | 特定服务(service)的UUID,例如:00001888-0000-1000-8000-00805f9b34fb。 | + + +## ServerResponse + +描述server端回复client端读/写请求的响应参数结构。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ----------- | ---- | ---- | -------------------------------------- | +| deviceId | string | 是 | 否 | 表示远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| transId | number | 是 | 否 | 表示请求的传输ID,与订阅的读/写请求事件携带的ID保持一致。 | +| status | number | 是 | 否 | 表示响应的状态,设置为0即可,表示正常。 | +| offset | number | 是 | 否 | 表示请求的读/写起始位置,与订阅的读/写请求事件携带的offset保持一致。 | +| value | ArrayBuffer | 是 | 否 | 表示回复响应的二进制数据。 | + + +## BLEConnectChangedState + +描述Gatt profile连接状态 。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | +| deviceId | string | 是 | 否 | 表示远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| state | [ProfileConnectionState](#profileconnectionstate) | 是 | 是 | 表示BLE连接状态的枚举。 | + + +## ProfileConnectionState + +枚举,蓝牙设备的profile连接状态。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ------------------- | ---- | -------------- | +| STATE_DISCONNECTED | 0 | 表示profile已断连。 | +| STATE_CONNECTING | 1 | 表示profile正在连接。 | +| STATE_CONNECTED | 2 | 表示profile已连接。 | +| STATE_DISCONNECTING | 3 | 表示profile正在断连。 | + + +## ScanFilter + +扫描过滤参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------------------------------------- | ----------- | ---- | ---- | ------------------------------------------------------------ | +| deviceId | string | 是 | 是 | 表示过滤的BLE设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| name | string | 是 | 是 | 表示过滤的BLE设备名。 | +| serviceUuid | string | 是 | 是 | 表示过滤包含该UUID服务的设备,例如:00001888-0000-1000-8000-00805f9b34fb。 | +| serviceUuidMask | string | 是 | 是 | 表示过滤包含该UUID服务掩码的设备,例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | +| serviceSolicitationUuid | string | 是 | 是 | 表示过滤包含该UUID服务请求的设备,例如:00001888-0000-1000-8000-00805F9B34FB。 | +| serviceSolicitationUuidMask | string | 是 | 是 | 表示过滤包含该UUID服务请求掩码的设备,例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | +| serviceData | ArrayBuffer | 是 | 是 | 表示过滤包含该服务相关数据的设备,例如:[0x90,0x00,0xF1,0xF2]。 | +| serviceDataMask | ArrayBuffer | 是 | 是 | 表示过滤包含该服务相关数据掩码的设备,例如:[0xFF,0xFF,0xFF,0xFF]。 | +| manufactureId | number | 是 | 是 | 表示过滤包含该制造商ID的设备,例如:0x0006。 | +| manufactureData | ArrayBuffer | 是 | 是 | 表示过滤包含该制造商相关数据的设备,例如:[0x1F,0x2F,0x3F]。 | +| manufactureDataMask | ArrayBuffer | 是 | 是 | 表示过滤包含该制造商相关数据掩码的设备,例如:[0xFF,0xFF,0xFF]。 | + + +## ScanOptions + +扫描的配置参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ----------------------- | ---- | ---- | -------------------------------------- | +| interval | number | 是 | 是 | 表示扫描结果上报延迟时间,默认值为0。 | +| dutyMode | [ScanDuty](#scanduty) | 是 | 是 | 表示扫描模式,默认值为SCAN_MODE_LOW_POWER。 | +| matchMode | [MatchMode](#matchmode) | 是 | 是 | 表示硬件的过滤匹配模式,默认值为MATCH_MODE_AGGRESSIVE。 | + + +## ScanDuty + +枚举,扫描模式。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------ | +| SCAN_MODE_LOW_POWER | 0 | 表示低功耗模式,默认值。 | +| SCAN_MODE_BALANCED | 1 | 表示均衡模式。 | +| SCAN_MODE_LOW_LATENCY | 2 | 表示低延迟模式。 | + + +## MatchMode + +枚举,硬件过滤匹配模式。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ---------------------------------------- | +| MATCH_MODE_AGGRESSIVE | 1 | 表示硬件上报扫描结果门限较低,比如扫描到的功率较低或者一段时间扫描到的次数较少也触发上报,默认值。 | +| MATCH_MODE_STICKY | 2 | 表示硬件上报扫描结果门限较高,更高的功率门限以及扫描到多次才会上报。 | + + +## ScanResult + +扫描结果上报数据。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ----------- | ---- | ---- | ---------------------------------- | +| deviceId | string | 是 | 否 | 表示扫描到的设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | +| rssi | number | 是 | 否 | 表示扫描到的设备的rssi值。 | +| data | ArrayBuffer | 是 | 否 | 表示扫描到的设备发送的广播包。 | + + +## BluetoothState + +枚举,蓝牙开关状态。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------------ | +| STATE_OFF | 0 | 表示蓝牙已关闭。 | +| STATE_TURNING_ON | 1 | 表示蓝牙正在打开。 | +| STATE_ON | 2 | 表示蓝牙已打开。 | +| STATE_TURNING_OFF | 3 | 表示蓝牙正在关闭。 | +| STATE_BLE_TURNING_ON | 4 | 表示蓝牙正在打开LE-only模式。 | +| STATE_BLE_ON | 5 | 表示蓝牙正处于LE-only模式。 | +| STATE_BLE_TURNING_OFF | 6 | 表示蓝牙正在关闭LE-only模式。 | + + +## AdvertiseSetting + +描述蓝牙低功耗设备发送广播的参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------- | ---- | ---- | ---------------------------------------- | +| interval | number | 是 | 是 | 表示广播间隔,最小值设置32个slot表示20ms,最大值设置16384个slot,默认值设置为1600个slot表示1s。 | +| txPower | number | 是 | 是 | 表示发送功率,最小值设置-127,最大值设置1,默认值设置-7,单位dbm。 | +| connectable | boolean | 是 | 是 | 表示是否是可连接广播,默认值设置为true。 | + + +## AdvertiseData + +描述BLE广播数据包的内容。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ---------------------------------------- | ---- | ---- | --------------------------- | +| serviceUuids | Array<string> | 是 | 是 | 表示要广播的服务 UUID 列表。 | +| manufactureData | Array<[ManufactureData](#manufacturedata)> | 是 | 是 | 表示要广播的广播的制造商信息列表。 | +| serviceData | Array<[ServiceData](#servicedata)> | 是 | 是 | 表示要广播的服务数据列表。 | + + +## ManufactureData + +描述BLE广播数据包的内容。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------------- | ------------------- | ---- | ---- | ------------------ | +| manufactureId | number | 是 | 是 | 表示制造商的ID,由蓝牙SIG分配。 | +| manufactureValue | ArrayBuffer | 是 | 是 | 表示制造商发送的制造商数据。 | + + +## ServiceData + +描述广播包中服务数据内容。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------ | ----------- | ---- | ---- | ---------- | +| serviceUuid | string | 是 | 是 | 表示服务的UUID。 | +| serviceValue | ArrayBuffer | 是 | 是 | 表示服务数据。 | + + +## PinRequiredParam + +描述配对请求参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | 是 | 否 | 表示要配对的设备ID。 | +| pinCode | string | 是 | 否 | 表示要配对的密钥。 | + + +## BondStateParam + +描述配对状态参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | 是 | 否 | 表示要配对的设备ID。 | +| state | BondState | 是 | 否 | 表示配对设备的状态。 | + + +## StateChangeParam + +描述profile状态改变参数。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------------------------------------------------- | ---- | ---- | ------------------------------- | +| deviceId | string | 是 | 否 | 表示蓝牙设备地址。 | +| state | [ProfileConnectionState](#profileconnectionstate) | 是 | 否 | 表示蓝牙设备的profile连接状态。 | + + +## DeviceClass + +描述蓝牙设备的类别。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ----------------------------------- | ---- | ---- | ---------------- | +| majorClass | [MajorClass](#majorclass) | 是 | 否 | 表示蓝牙设备主要类别的枚举。 | +| majorMinorClass | [MajorMinorClass](#majorminorclass) | 是 | 否 | 表示主要次要蓝牙设备类别的枚举。 | +| classOfDevice | number | 是 | 否 | 表示设备类别。 | + + + +## MajorClass + +枚举,蓝牙设备主要类别。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ------------------- | ------ | ---------- | +| MAJOR_MISC | 0x0000 | 表示杂项设备。 | +| MAJOR_COMPUTER | 0x0100 | 表示计算机设备。 | +| MAJOR_PHONE | 0x0200 | 表示手机设备。 | +| MAJOR_NETWORKING | 0x0300 | 表示网络设备。 | +| MAJOR_AUDIO_VIDEO | 0x0400 | 表示音频和视频设备。 | +| MAJOR_PERIPHERAL | 0x0500 | 表示外围设备。 | +| MAJOR_IMAGING | 0x0600 | 表示成像设备。 | +| MAJOR_WEARABLE | 0x0700 | 表示可穿戴设备。 | +| MAJOR_TOY | 0x0800 | 表示玩具设备。 | +| MAJOR_HEALTH | 0x0900 | 表示健康设备。 | +| MAJOR_UNCATEGORIZED | 0x1F00 | 表示未分类设备。 | + + +## MajorMinorClass + +枚举,主要次要蓝牙设备类别。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ---------------------------------------- | ------ | --------------- | +| COMPUTER_UNCATEGORIZED | 0x0100 | 表示未分类计算机设备。 | +| COMPUTER_DESKTOP | 0x0104 | 表示台式计算机设备。 | +| COMPUTER_SERVER | 0x0108 | 表示服务器设备。 | +| COMPUTER_LAPTOP | 0x010C | 表示便携式计算机设备。 | +| COMPUTER_HANDHELD_PC_PDA | 0x0110 | 表示手持式计算机设备。 | +| COMPUTER_PALM_SIZE_PC_PDA | 0x0114 | 表示掌上电脑设备。 | +| COMPUTER_WEARABLE | 0x0118 | 表示可穿戴计算机设备。 | +| COMPUTER_TABLET | 0x011C | 表示平板电脑设备。 | +| PHONE_UNCATEGORIZED | 0x0200 | 表示未分类手机设备。 | +| PHONE_CELLULAR | 0x0204 | 表示便携式手机设备。 | +| PHONE_CORDLESS | 0x0208 | 表示无线电话设备。 | +| PHONE_SMART | 0x020C | 表示智能手机设备。 | +| PHONE_MODEM_OR_GATEWAY | 0x0210 | 表示调制解调器或网关手机设备。 | +| PHONE_ISDN | 0x0214 | 表示ISDN手机设备。 | +| NETWORK_FULLY_AVAILABLE | 0x0300 | 表示网络完全可用设备。 | +| NETWORK_1_TO_17_UTILIZED | 0x0320 | 表示使用网络1到17设备。 | +| NETWORK_17_TO_33_UTILIZED | 0x0340 | 表示使用网络17到33设备。 | +| NETWORK_33_TO_50_UTILIZED | 0x0360 | 表示使用网络33到50设备。 | +| NETWORK_60_TO_67_UTILIZED | 0x0380 | 表示使用网络60到67设备。 | +| NETWORK_67_TO_83_UTILIZED | 0x03A0 | 表示使用网络67到83设备。 | +| NETWORK_83_TO_99_UTILIZED | 0x03C0 | 表示使用网络83到99设备。 | +| NETWORK_NO_SERVICE | 0x03E0 | 表示网络无服务设备。 | +| AUDIO_VIDEO_UNCATEGORIZED | 0x0400 | 表示未分类音频视频设备。 | +| AUDIO_VIDEO_WEARABLE_HEADSET | 0x0404 | 表示可穿戴式音频视频设备。 | +| AUDIO_VIDEO_HANDSFREE | 0x0408 | 表示免提音频视频设备。 | +| AUDIO_VIDEO_MICROPHONE | 0x0410 | 表示麦克风音频视频设备。 | +| AUDIO_VIDEO_LOUDSPEAKER | 0x0414 | 表示扬声器音频视频设备。 | +| AUDIO_VIDEO_HEADPHONES | 0x0418 | 表示头戴式音频视频设备。 | +| AUDIO_VIDEO_PORTABLE_AUDIO | 0x041C | 表示便携式音频视频设备。 | +| AUDIO_VIDEO_CAR_AUDIO | 0x0420 | 表示汽车音频视频设备。 | +| AUDIO_VIDEO_SET_TOP_BOX | 0x0424 | 表示机顶盒音频视频设备。 | +| AUDIO_VIDEO_HIFI_AUDIO | 0x0428 | 表示高保真音响设备。 | +| AUDIO_VIDEO_VCR | 0x042C | 表示录像机音频视频设备。 | +| AUDIO_VIDEO_VIDEO_CAMERA | 0x0430 | 表示照相机音频视频设备。 | +| AUDIO_VIDEO_CAMCORDER | 0x0434 | 表示摄像机音频视频设备。 | +| AUDIO_VIDEO_VIDEO_MONITOR | 0x0438 | 表示监视器音频视频设备。 | +| AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER | 0x043C | 表示视频显示器和扬声器设备。 | +| AUDIO_VIDEO_VIDEO_CONFERENCING | 0x0440 | 表示音频视频会议设备。 | +| AUDIO_VIDEO_VIDEO_GAMING_TOY | 0x0448 | 表示游戏玩具音频视频设备。 | +| PERIPHERAL_NON_KEYBOARD_NON_POINTING | 0x0500 | 表示非键盘非指向外围设备。 | +| PERIPHERAL_KEYBOARD | 0x0540 | 表示外设键盘设备。 | +| PERIPHERAL_POINTING_DEVICE | 0x0580 | 表示定点装置外围设备。 | +| PERIPHERAL_KEYBOARD_POINTING | 0x05C0 | 表示键盘指向外围设备。 | +| PERIPHERAL_UNCATEGORIZED | 0x0500 | 表示未分类外围设备。 | +| PERIPHERAL_JOYSTICK | 0x0504 | 表示周边操纵杆设备。 | +| PERIPHERAL_GAMEPAD | 0x0508 | 表示周边游戏板设备。 | +| PERIPHERAL_REMOTE_CONTROL | 0x05C0 | 表示远程控制外围设备。 | +| PERIPHERAL_SENSING_DEVICE | 0x0510 | 表示外围传感设备设备。 | +| PERIPHERAL_DIGITIZER_TABLET | 0x0514 | 表示外围数字化仪平板电脑设备。 | +| PERIPHERAL_CARD_READER | 0x0518 | 表示外围读卡器设备。 | +| PERIPHERAL_DIGITAL_PEN | 0x051C | 表示外设数码笔设备。 | +| PERIPHERAL_SCANNER_RFID | 0x0520 | 表示射频识别扫描仪外围设备。 | +| PERIPHERAL_GESTURAL_INPUT | 0x0522 | 表示手势输入外围设备。 | +| IMAGING_UNCATEGORIZED | 0x0600 | 表示未分类的图像设备。 | +| IMAGING_DISPLAY | 0x0610 | 表示图像显示设备。 | +| IMAGING_CAMERA | 0x0620 | 表示成像照相机设备。 | +| IMAGING_SCANNER | 0x0640 | 表示成像扫描仪设备。 | +| IMAGING_PRINTER | 0x0680 | 表示成像打印机设备。 | +| WEARABLE_UNCATEGORIZED | 0x0700 | 表示未分类的可穿戴设备。 | +| WEARABLE_WRIST_WATCH | 0x0704 | 表示可穿戴腕表设备。 | +| WEARABLE_PAGER | 0x0708 | 表示可穿戴寻呼机设备。 | +| WEARABLE_JACKET | 0x070C | 表示夹克可穿戴设备。 | +| WEARABLE_HELMET | 0x0710 | 表示可穿戴头盔设备。 | +| WEARABLE_GLASSES | 0x0714 | 表示可穿戴眼镜设备。 | +| TOY_UNCATEGORIZED | 0x0800 | 表示未分类的玩具设备。 | +| TOY_ROBOT | 0x0804 | 表示玩具机器人设备。 | +| TOY_VEHICLE | 0x0808 | 表示玩具车设备。 | +| TOY_DOLL_ACTION_FIGURE | 0x080C | 表示人形娃娃玩具设备。 | +| TOY_CONTROLLER | 0x0810 | 表示玩具控制器设备。 | +| TOY_GAME | 0x0814 | 表示玩具游戏设备。 | +| HEALTH_UNCATEGORIZED | 0x0900 | 表示未分类健康设备。 | +| HEALTH_BLOOD_PRESSURE | 0x0904 | 表示血压健康设备。 | +| HEALTH_THERMOMETER | 0x0908 | 表示温度计健康设备。 | +| HEALTH_WEIGHING | 0x090C | 表示体重健康设备。 | +| HEALTH_GLUCOSE | 0x0910 | 表示葡萄糖健康设备。 | +| HEALTH_PULSE_OXIMETER | 0x0914 | 表示脉搏血氧仪健康设备。 | +| HEALTH_PULSE_RATE | 0x0918 | 表示脉搏率健康设备。 | +| HEALTH_DATA_DISPLAY | 0x091C | 表示数据显示健康设备。 | +| HEALTH_STEP_COUNTER | 0x0920 | 表示阶梯计数器健康设备。 | +| HEALTH_BODY_COMPOSITION_ANALYZER | 0x0924 | 表示身体成分分析仪健康设备。 | +| HEALTH_PEAK_FLOW_MONITOR | 0x0928 | 表示湿度计健康设备。 | +| HEALTH_MEDICATION_MONITOR | 0x092C | 表示药物监视仪健康设备。 | +| HEALTH_KNEE_PROSTHESIS | 0x0930 | 表示膝盖假肢健康设备。 | +| HEALTH_ANKLE_PROSTHESIS | 0x0934 | 表示脚踝假肢健康设备。 | +| HEALTH_GENERIC_HEALTH_MANAGER | 0x0938 | 表示通用健康管理设备。 | +| HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | 表示个人移动健康设备。 | + + +## PlayingState + +枚举,蓝牙A2DP 播放状态。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| ----------------- | ------ | ------- | +| STATE_NOT_PLAYING | 0x0000 | 表示未播放。 | +| STATE_PLAYING | 0x0001 | 表示正在播放。 | + + +## ProfileId + +蓝牙profile枚举,API9新增PROFILE_HID_HOST,PROFILE_PAN_NETWORK。 + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +| 名称 | 值 | 说明 | +| -------------------------------- | ------ | --------------- | +| PROFILE_A2DP_SOURCE | 1 | 表示A2DP profile。 | +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | 表示HFP profile。 | +| PROFILE_HID_HOST | 6 | 表示HID profile。 | +| PROFILE_PAN_NETWORK | 7 | 表示PAN profile。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 15103ae6cd763d2b54bb4c11955df34ad1be5325..a81e2dba60db16e30001d53b8124430df6f24beb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -183,7 +183,7 @@ bundle.getBundleInstaller().then(installer => { | statusMessage | string | 是 | 否 | 表示安装或卸载的字符串结果信息。取值范围包括:
"SUCCESS" : 安装成功,
"STATUS_INSTALL_FAILURE": 安装失败(不存在安装文件),
"STATUS_INSTALL_FAILURE_ABORTED": 安装中止,
"STATUS_INSTALL_FAILURE_INVALID": 安装参数无效,
"STATUS_INSTALL_FAILURE_CONFLICT": 安装冲突(常见于升级和已有应用基本信息不一致),
"STATUS_INSTALL_FAILURE_STORAGE": 存储包信息失败,
"STATUS_INSTALL_FAILURE_INCOMPATIBLE": 安装不兼容(常见于版本降级安装或者签名信息错误),
"STATUS_UNINSTALL_FAILURE": 卸载失败(不存在卸载的应用),
"STATUS_UNINSTALL_FAILURE_ABORTED": 卸载中止(没有使用),
"STATUS_UNINSTALL_FAILURE_ABORTED": 卸载冲突(卸载系统应用失败, 结束应用进程失败),
"STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT": 安装失败(下载超时),
"STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED": 安装失败(下载失败),
"STATUS_RECOVER_FAILURE_INVALID": 恢复预置应用失败,
"STATUS_ABILITY_NOT_FOUND": Ability未找到,
"STATUS_BMS_SERVICE_ERROR": BMS服务错误,
"STATUS_FAILED_NO_SPACE_LEFT": 设备空间不足,
"STATUS_GRANT_REQUEST_PERMISSIONS_FAILED": 应用授权失败,
"STATUS_INSTALL_PERMISSION_DENIED": 缺少安装权限,
"STATUS_UNINSTALL_PERMISSION_DENIED": 缺少卸载权限| ## 获取应用的沙箱路径 -对于FA模型,应用的沙箱路径可以通过[Context](js-apis-inner-app-context.md)中的方法获取;对于Stage模型,应用的沙箱路径可以通过[Context](js-apis-ability-context.md#abilitycontext)中的属性获取。下面以获取沙箱文件路径为例。 +对于FA模型,应用的沙箱路径可以通过[Context](js-apis-inner-app-context.md)中的方法获取;对于Stage模型,应用的沙箱路径可以通过[Context](js-apis-inner-application-uiAbilityContext.md#abilitycontext)中的属性获取。下面以获取沙箱文件路径为例。 **示例:** ``` ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md new file mode 100755 index 0000000000000000000000000000000000000000..aaf0668397c0db56c7e0a0ff22eabab2325fc20d --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-overlayModuleInfo.md @@ -0,0 +1,18 @@ +# OverlayModuleInfo + +> **说明:** +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +OverlayModuleInfo信息,系统应用可以通过[overlay.getOverlayModuleInfoByBundleName](js-apis-overlay.md#overlaygetoverlaymoduleinfobybundlename)获取指定应用的overlay特征module的OverlayModuleInfo信息,三方应用可以通过[overlay.getOverlayModuleInfo](js-apis-overlay.md#overlaygetoverlaymoduleinfo)获取当前应用中overlay特征module的OverlayModuleInfo信息。 + +## OverlayModuleInfo + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Overlay。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------- | ---------------------------------------------------| ---- | ---- | ---------------------------------------------- | +| bundleName | string | 是 | 否 | overlay特征module所属的应用的bundle名称。 | +| moduleName | string | 是 | 否 | overlay特征module的HAP名称。 | +| targetModuleName | string | 是 | 否 | overlay特征module指定的目标module的HAP名称。 | +| priority | number | 是 | 否 | overlay特征module的优先级。 | +| state | number | 是 | 否 | overlay特征module的禁用使能状态。0代表禁用状态; 1代表使能状态。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-sharedBundleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-sharedBundleInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..7a3f872517b48c574436a6f94ca3d646a8022cf7 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-sharedBundleInfo.md @@ -0,0 +1,32 @@ +# SharedBundleInfo + +> **说明:** +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +共享包信息,通过接口[bundleManager.getSharedBundleInfo](js-apis-bundleManager.md)获取。 + +## SharedBundleInfo + + 共享包信息。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------------- | ------------------------------ | ---- | ---- | ---------------------- | +| name | string | 是 | 否 | 应用共享包名称。 | +| compatiblePolicy | bundleManager.CompatiblePolicy | 是 | 否 | 共享包兼容策略的类型。 | +| sharedModuleInfo | Array\ | 是 | 否 | 应用共享模块信息。 | + +## SharedModuleInfo + +共享模块信息。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------- | ------ | ---- | ---- | -------------------------- | +| name | string | 是 | 否 | 共享包模块名称。 | +| versionCode | number | 是 | 否 | 共享包的版本号。 | +| versionName | string | 是 | 否 | 共享包的版本文本描述信息。 | +| description | string | 是 | 否 | 共享包的模块描述信息。 | +| descriptionId | number | 是 | 否 | 共享包描述的资源id值。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md index 4bfaae9a01ad673d9afefbedd94f8113d1e9272c..3380547721122aadf017c595c8cf25d052d15af9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @@ -111,6 +111,7 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。 | ENTERPRISE_ADMIN | 11 | [EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md):企业设备管理扩展能力,提供企业管理时处理管理事件的能力,比如设备上应用安装事件、锁屏密码输入错误次数过多事件等。 | | THUMBNAIL | 13 | ThumbnailExtensionAbility:文件缩略图扩展能力,用于为文件提供图标缩略图的能力。预留能力,当前暂未支持。 | | PREVIEW | 14 | PreviewExtensionAbility:文件预览扩展能力,提供文件预览的能力,其他应用可以直接在应用中嵌入显示。预留能力,当前暂未支持。 | +| PRINT10+ | 15 | PrintExtensionAbility:文件打印扩展能力,提供应用打印照片、文档等办公场景。当前支持图片打印,文档类型暂未支持。 | | UNSPECIFIED | 255 | 不指定类型,配合queryExtensionAbilityInfo接口可以查询所有类型的ExtensionAbility。 | @@ -2214,7 +2215,7 @@ try { ### bundleManager.getProfileByAbility -getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback>): void; +getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void; 以异步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,使用callback形式返回结果。 @@ -2265,7 +2266,7 @@ try { ### bundleManager.getProfileByAbility -getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise>; +getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise\\>; 以异步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,使用Promise形式返回结果。 @@ -2335,7 +2336,7 @@ try { ### bundleManager.getProfileByExtensionAbility -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback>): void; +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void; 以异步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,使用callback形式返回结果。 @@ -2385,7 +2386,7 @@ try { ### bundleManager.getProfileByExtensionAbility -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise>; +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise\\>; 以异步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,使用Promise形式返回结果。 @@ -2658,7 +2659,6 @@ try { ### bundleManager.getApplicationInfoSync getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); -getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); 以同步方法根据给定的bundleName、applicationFlags和userId获取ApplicationInfo。 @@ -2709,6 +2709,42 @@ try { } ``` +### bundleManager.getApplicationInfoSync + +getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); + +以同步方法根据给定的bundleName、applicationFlags获取ApplicationInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | -------------------------- | ---- | ----------------------------------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| applicationFlags | [number](#applicationflag) | 是 | 表示用于指定将返回的ApplicationInfo对象中包含的信息。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | ------------------------- | +| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 返回ApplicationInfo对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700026 | The specified bundle is disabled. | + +**示例:** + ```ts import bundleManager from '@ohos.bundle.bundleManager'; import hilog from '@ohos.hilog'; @@ -2726,7 +2762,6 @@ try { ### bundleManager.getBundleInfoSync getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag), userId: number): [BundleInfo](js-apis-bundleManager-bundleInfo.md); -getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); 以同步方法根据给定的bundleName、bundleFlags和userId获取BundleInfo。 @@ -2742,7 +2777,7 @@ getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [Bund | ----------- | ------ | ---- | -------------------------------------------------------- | | bundleName | string | 是 | 表示应用程序的bundleName。 | | bundleFlags | [number](#bundleflag) | 是 | 表示用于指定将返回的BundleInfo对象中包含的信息的标志。 | -| userId | number | 否 | 表示用户ID。 | +| userId | number | 是 | 表示用户ID。 | **返回值:** @@ -2777,6 +2812,42 @@ try { } ``` +### bundleManager.getBundleInfoSync + +getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); + +以同步方法根据给定的bundleName、bundleFlags获取BundleInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------------- | ---- | ------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定将返回的BundleInfo对象中包含的信息的标志。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | 返回BundleInfo对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700026 | The specified bundle is disabled. | + +**示例:** + ```ts import bundleManager from '@ohos.bundle.bundleManager'; import hilog from '@ohos.hilog'; @@ -2789,3 +2860,222 @@ try { hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` + +### bundleManager.getSharedBundleInfo10+ + +getSharedBundleInfo(bundleName: string, moduleName: string, callback: AsyncCallback\\>): void; + +以异步的方法获取指定的共享包信息,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| moduleName | string | 是 | 表示被查询的module的name。 | +| callback | AsyncCallback\\> | 是 | 回调函数,当获取成功时,err为null,data为获取的指定共享包信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'library'; + +try { + bundleManager.getSharedBundleInfo(bundleName, moduleName, (err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getSharedBundleInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getSharedBundleInfo10+ + +function getSharedBundleInfo(bundleName: string, moduleName: string): Promise\\>; + +以异步的方法获取指定的共享包信息,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| moduleName | string | 是 | 表示被查询的module的name。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ----------------------------------- | +| Promise\\> | Promise对象,返回指定的共享包信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'library'; + +try { + bundleManager.getSharedBundleInfo(bundleName, moduleName).then((data) => { + hilog.info(0x0000, 'testTag', 'getSharedBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed. Cause: %{public}s', err.message); +} +``` + +### bundleManager.getAllSharedBundleInfo10+ + +getAllSharedBundleInfo(callback: AsyncCallback\\>): void; + +以异步的方法获取所有的共享包信息,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\\> | 是 | 回调函数,当获取成功时,err为null,data为获所有的共享包信息。 | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; + +try { + bundleManager.getAllSharedBundleInfo((err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getAllSharedBundleInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getAllSharedBundleInfo10+ + +function getAllSharedBundleInfo(): Promise\\>; + +以异步的方法获取所有的共享包信息,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ----------------------------------- | +| Promise\\> | Promise对象,返回所有的共享包信息。 | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; + +try { + bundleManager.getAllSharedBundleInfo().then((data) => { + hilog.info(0x0000, 'testTag', 'getAllSharedBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed. Cause: %{public}s', err.message); +} +``` + +## CompatiblePolicy + +标识共享库的版本兼容类型。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 值 | 说明 | +| ---------------------- | ---- | -------------------------------- | +| BACKWARD_COMPATIBILITY | 1 | 该字段表明共享库是向后兼容类型。 | + +## ModuleType + +标识模块类型。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 值 | 说明 | +| ------- | ---- | -------------------- | +| ENTRY | 1 | 应用的主模块。 | +| FEATURE | 2 | 应用的动态特性模块。 | +| SHARED | 3 | 应用的动态共享库模块。 | + +## BundleType + +标识应用的类型。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 值 | 说明 | +| -------------- | ---- | --------------- | +| APP | 0 | 该Bundle是普通应用程序。 | +| ATOMIC_SERVICE | 1 | 该Bundle是元服务。 | + +## AtomicServiceModuleType + +标识在元服务分包时的分包类型。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 值 | 说明 | +| ------ | ---- | --------------------------- | +| NORMAL | 0 | 元服务中的页面包。 | +| MAIN | 1 | 元服务中的落地页包. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md index 1660ff419222d10b9fc90290191d0e86712aad7e..8b00ad32d9ad9f50939f3898ab8805876e8b4819 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -33,7 +33,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; ## bundleMonitor.on -on(type: BundleChangedEvent, callback: callback\): void; +on(type: BundleChangedEvent, callback: Callback\): void; 注册监听应用的安装,卸载,更新。 @@ -66,7 +66,7 @@ try { ## bundleMonitor.off -off(type: BundleChangedEvent, callback?: callback\): void; +off(type: BundleChangedEvent, callback?: Callback\): void; 注销监听应用的安装,卸载,更新。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md index 78c21552f22004a4eec28c0c42844ac14faf3a99..911631d7e8922b32a9a6a9c46c74b5c7f10ad4a5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-call.md +++ b/zh-cn/application-dev/reference/apis/js-apis-call.md @@ -14,12 +14,16 @@ import call from '@ohos.telephony.call'; ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, callback: AsyncCallback\): void 拨打电话。使用callback异步回调。 +>**说明:** +> +>从API version 6 开始支持,从API version 9 开始废弃,建议使用[dialCall](#calldialcall9)替代。 + **需要权限**:ohos.permission.PLACE_CALL **系统能力**:SystemCapability.Telephony.CallManager @@ -40,12 +44,16 @@ call.dial("138xxxxxxxx", (err, data) => { ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\): void 拨打电话,可设置通话参数。使用callback异步回调。 +>**说明:** +> +>从API version 6 开始支持,从API version 9 开始废弃,建议使用[dialCall](#calldialcall9)替代。 + **需要权限**:ohos.permission.PLACE_CALL **系统能力**:SystemCapability.Telephony.CallManager @@ -69,12 +77,16 @@ call.dial("138xxxxxxxx", { ``` -## call.dial +## call.dial(deprecated) dial\(phoneNumber: string, options?: DialOptions\): Promise 拨打电话,可设置通话参数。使用Promise异步回调。 +>**说明:** +> +>从API version 6 开始支持,从API version 9 开始废弃,建议使用[dialCall](#calldialcall9)替代。 + **需要权限**:ohos.permission.PLACE_CALL **系统能力**:SystemCapability.Telephony.CallManager @@ -120,10 +132,10 @@ dialCall\(phoneNumber: string, callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ---------------------------- | ---- | --------------------------------------- | -| phoneNumber | string | 是 | 电话号码。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数,返回true为成功,false为失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------- |---------------------------| ---- |-------------------------| +| phoneNumber | string | 是 | 电话号码。 | +| callback | AsyncCallback<void> | 是 | 以callback形式异步返回拨打电话的结果。 | **错误码:** @@ -159,11 +171,11 @@ dialCall\(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ----------------------------------- | ---- | ------------------------------------ | -| phoneNumber | string | 是 | 电话号码。 | -| options | [DialCallOptions](#dialcalloptions9)| 是 | 通话参数,携带呼叫的其他配置信息。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数,返回true为成功,false为失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------- |--------------------------------------| ---- | ------------------------------------ | +| phoneNumber | string | 是 | 电话号码。 | +| options | [DialCallOptions](#dialcalloptions9) | 是 | 通话参数,携带呼叫的其他配置信息。 | +| callback | AsyncCallback<void> | 是 | 以callback形式异步返回拨打电话的结果。 | **错误码:** @@ -207,7 +219,13 @@ dialCall\(phoneNumber: string, options?: DialCallOptions\): Promise | 参数名 | 类型 | 必填 | 说明 | | ----------- | ----------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | 是 | 电话号码。 | -| options | [DialCallOptions](#dialcalloptions9)| 否 | 通话参数,选择为语音通话还是视频通话。 | +| options | [DialCallOptions](#dialcalloptions9)| 否 | 通话参数,携带呼叫的其他配置信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------------------- | +| Promise<void> | 以Promise形式异步返回拨打电话的结果。 | **错误码:** @@ -223,12 +241,17 @@ dialCall\(phoneNumber: string, options?: DialCallOptions\): Promise **示例:** ```js -try { - call.dialCall('138xxxxxxxx'); +let promise = call.dialCall("138xxxxxxxx", { + accountId: 0, + videoState: 0, + dialScene: 0, + dialType: 0, +}); +promise.then(data => { console.log(`dialCall success, promise: data->${JSON.stringify(data)}`); -} catch (error) { - console.log(`dialCall fail, promise: err->${JSON.stringify(error)}`); -} +}).catch(err => { + console.error(`dialCall fail, promise: err->${JSON.stringify(err)}`); +}); ``` @@ -815,9 +838,9 @@ promise.then(data => { ``` -## call.answer7+ +## call.answerCall9+ -answer\(callId: number, callback: AsyncCallback\): void +answerCall\(callId: number, callback: AsyncCallback\): void 接听来电。使用callback异步回调。 @@ -848,15 +871,15 @@ answer\(callId: number, callback: AsyncCallback\): void **示例:** ```js -call.answer(1, (err, data) => { +call.answerCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.answer7+ +## call.answerCall9+ -answer(callId?: number\): Promise +answerCall(callId?: number\): Promise 接听来电。使用Promise异步回调。 @@ -892,20 +915,20 @@ answer(callId?: number\): Promise **示例:** ```js -let promise = call.answer(1); +let promise = call.answerCall(1); promise.then(data => { - console.log(`answer success, promise: data->${JSON.stringify(data)}`); + console.log(`answerCall success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`answer fail, promise: err->${JSON.stringify(err)}`); + console.error(`answerCall fail, promise: err->${JSON.stringify(err)}`); }); ``` -## call.hangup7+ +## call.answerCall9+ -hangup\(callId: number, callback: AsyncCallback\): void +answerCall\(callback: AsyncCallback\): void -挂断电话。使用callback异步回调。 +接听来电。使用callback异步回调。 **系统接口:** 此接口为系统接口。 @@ -915,10 +938,9 @@ hangup\(callId: number, callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ----------------------------------------------- | -| callId | number | 是 | 呼叫id。可以通过订阅callDetailsChange事件获得。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -934,17 +956,17 @@ hangup\(callId: number, callback: AsyncCallback\): void **示例:** ```js -call.hangup(1, (err, data) => { +call.answerCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.answer9+ +## call.hangUpCall9+ -answer\(callback: AsyncCallback\): void +hangUpCall\(callId: number, callback: AsyncCallback\): void -接听来电。使用callback异步回调。 +挂断电话。使用callback异步回调。 **系统接口:** 此接口为系统接口。 @@ -954,9 +976,10 @@ answer\(callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | 是 | 呼叫id。可以通过订阅callDetailsChange事件获得。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -972,15 +995,15 @@ answer\(callback: AsyncCallback\): void **示例:** ```js -call.answer((err, data) => { +call.hangUpCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.hangup7+ +## call.hangUpCall9+ -hangup\(callId?: number\): Promise +hangUpCall\(callId?: number\): Promise 挂断电话。使用Promise异步回调。 @@ -1016,18 +1039,18 @@ hangup\(callId?: number\): Promise **示例:** ```js -let promise = call.hangup(1); +let promise = call.hangUpCall(1); promise.then(data => { - console.log(`hangup success, promise: data->${JSON.stringify(data)}`); + console.log(`hangUpCall success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`hangup fail, promise: err->${JSON.stringify(err)}`); + console.error(`hangUpCall fail, promise: err->${JSON.stringify(err)}`); }); ``` -## call.hangup9+ +## call.hangUpCall9+ -hangup\(callback: AsyncCallback\): void +hangUpCall\(callback: AsyncCallback\): void 挂断电话。使用callback异步回调。 @@ -1058,15 +1081,15 @@ hangup\(callback: AsyncCallback\): void **示例:** ```js -call.hangup((err, data) => { +call.hangUpCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ +## call.rejectCall9+ -reject(callId: number, callback: AsyncCallback\): void +rejectCall(callId: number, callback: AsyncCallback\): void 拒绝来电。使用callback异步回调。 @@ -1098,15 +1121,15 @@ reject(callId: number, callback: AsyncCallback\): void **示例:** ```js -call.reject(1, (err, data) => { +call.rejectCall(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ +## call.rejectCall9+ -reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void +rejectCall\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void 拒绝来电。使用callback异步回调。 @@ -1141,15 +1164,15 @@ reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback { +call.rejectCall(1, rejectMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject7+ +## call.rejectCall9+ -reject(callId?: number, options?: RejectMessageOptions\): Promise +rejectCall(callId?: number, options?: RejectMessageOptions\): Promise 拒绝来电。使用Promise异步回调。 @@ -1198,9 +1221,9 @@ promise.then(data => { ``` -## call.reject9+ +## call.rejectCall9+ -reject\(callback: AsyncCallback\): void +rejectCall\(callback: AsyncCallback\): void 拒绝来电。使用callback异步回调。 @@ -1230,15 +1253,15 @@ reject\(callback: AsyncCallback\): void **示例:** ```js -call.reject((err, data) => { +call.rejectCall((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.reject9+ +## call.rejectCall9+ -reject\(options: RejectMessageOptions, callback: AsyncCallback\): void +rejectCall\(options: RejectMessageOptions, callback: AsyncCallback\): void 拒绝来电。使用callback异步回调。 @@ -1272,7 +1295,7 @@ reject\(options: RejectMessageOptions, callback: AsyncCallback\): void let rejectMessageOptions={ messageContent: "拦截陌生号码" } -call.reject(rejectMessageOptions, (err, data) => { +call.rejectCall(rejectMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -3844,7 +3867,7 @@ promise.then(data => { 拨打电话的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ----------------------------------------------------------------------------------------------- | @@ -3858,7 +3881,7 @@ promise.then(data => { 拨打电话的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | @@ -3871,7 +3894,7 @@ promise.then(data => { 通话状态码。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------ | ---- | ------------------------------------------------------------ | @@ -3884,7 +3907,7 @@ promise.then(data => { 判断是否是紧急电话号码的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ---------------------------------------------- | @@ -3894,7 +3917,7 @@ promise.then(data => { 格式化号码的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | ---------------------------------------------------------- | @@ -3906,7 +3929,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------------- | ---- | ------------------ | @@ -3922,7 +3945,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -3938,7 +3961,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------------------------------------- | ---- | -------------------------- | @@ -3957,7 +3980,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------------------------- | ---- | ---------------- | @@ -3975,7 +3998,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------------------- | ---- | ------------ | @@ -3990,7 +4013,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------------- | ---- | ------------ | @@ -4005,7 +4028,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | --------------- | ---------------------------------------- | ---- | -------------- | @@ -4026,7 +4049,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------------------- | ---- | -------------- | @@ -4041,7 +4064,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------- | ---- | ------------ | @@ -4056,7 +4079,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------- | ---- | -------- | @@ -4069,7 +4092,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------- | ---- | -------------- | @@ -4089,7 +4112,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------- | ---- | ------------ | @@ -4103,7 +4126,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ----------------------------- | ---- | ------------ | @@ -4116,7 +4139,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------ | ---- | -------------- | @@ -4128,7 +4151,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------ | ---- | --------------- | @@ -4141,7 +4164,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------- | ---- | ------------ | @@ -4155,7 +4178,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ---------------- | @@ -4169,7 +4192,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | -------- | @@ -4181,7 +4204,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ---------------- | @@ -4198,7 +4221,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -4211,7 +4234,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------- | ---- | -------- | @@ -4224,7 +4247,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------- | ---- | -------- | @@ -4237,7 +4260,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------ | ---- | --------------- | @@ -4250,7 +4273,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------------------------------------------ | ---- | --------------------------------------- | @@ -4340,7 +4363,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | -------------------------------- | ---- | --------------- | @@ -4353,7 +4376,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------- | ---- | ------------- | @@ -4366,7 +4389,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------ | ---- | -------- | 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 9bb488cd0f25aa51bc4b9c220d21f4c82d70e082..3c17b40889115925dd7faba5c15a46d80ce821ac 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -31,6 +31,15 @@ getCameraManager(context: Context): CameraManager | ----------------------------------------------- | ---------------------------- | | [CameraManager](#cameramanager) | 相机管理器。 | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -255,6 +264,14 @@ createCameraInput(camera: CameraDevice): CameraInput | ---------- | ----------------------------- | | [CameraInput](#camerainput) | CameraInput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -291,6 +308,14 @@ createCameraInput(position: CameraPosition, type: CameraType): CameraInput | ---------- | ----------------------------- | | [CameraInput](#camerainput) | CameraInput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -327,6 +352,14 @@ createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput | ---------- | ----------------------------- | | [PreviewOutput](#previewoutput) | PreviewOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -361,6 +394,14 @@ createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput | ---------- | ----------------------------- | | [PhotoOutput](#photooutput) | PhotoOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -395,6 +436,14 @@ createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput | ---------- | ----------------------------- | | [VideoOutput](#videooutput) | VideoOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -428,6 +477,14 @@ createMetadataOutput(metadataObjectTypes:Array): MetadataOu | ---------- | ----------------------------- | | [MetadataOutput](#metadataoutput) | MetadataOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | + **示例:** ```js @@ -455,6 +512,14 @@ createCaptureSession(): CaptureSession | ---------- | ----------------------------- | | [CaptureSession](#capturesession) | CaptureSession实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -630,6 +695,16 @@ open\(callback: AsyncCallback\): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400107 | Can not use camera cause of conflict. | +| 7400108 | Camera disabled cause of security reason. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -656,6 +731,16 @@ open(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400107 | Can not use camera cause of conflict. | +| 7400108 | Camera disabled cause of security reason. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -680,6 +765,14 @@ close\(callback: AsyncCallback\): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -706,6 +799,14 @@ close(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -823,6 +924,14 @@ beginConfig(): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400105 | Session config locked. | + **示例:** ```js @@ -848,6 +957,15 @@ commitConfig(callback: AsyncCallback): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400102 | Operation not allow. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -874,6 +992,15 @@ commitConfig(): Promise | -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400102 | Operation not allow. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -905,6 +1032,15 @@ addInput(cameraInput: CameraInput): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **示例:** ```js @@ -936,6 +1072,15 @@ removeInput(cameraInput: CameraInput): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **示例:** ```js @@ -967,6 +1112,15 @@ addOutput(previewOutput: CameraOutput): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **示例:** ```js @@ -998,6 +1152,15 @@ removeOutput(previewOutput: CameraOutput): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400102 | Operation not allow. | + **示例:** ```js @@ -1023,6 +1186,15 @@ start\(callback: AsyncCallback\): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1049,6 +1221,15 @@ start\(\): Promise | -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1073,6 +1254,14 @@ stop\(callback: AsyncCallback\): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1099,6 +1288,14 @@ stop(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1123,6 +1320,14 @@ release\(callback: AsyncCallback\): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1149,6 +1354,14 @@ release(): Promise | -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -1173,6 +1386,14 @@ hasFlash(): boolean | ---------- | ----------------------------- | | boolean | 返回true表示设备支持闪光灯。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1204,6 +1425,14 @@ isFlashModeSupported(flashMode: FlashMode): boolean | ---------- | ----------------------------- | | boolean | 返回true表示支持该闪光灯模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1240,6 +1469,14 @@ setFlashMode(flashMode: FlashMode): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1265,6 +1502,14 @@ getFlashMode(): FlashMode | ---------- | ----------------------------- | | [FlashMode](#flashmode) | 获取当前设备的闪光灯模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1296,6 +1541,14 @@ isExposureModeSupported(aeMode: ExposureMode): boolean; | ---------- | ----------------------------- | | boolean | 获取是否支持曝光模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1321,6 +1574,14 @@ getExposureMode(): ExposureMode | ---------- | ----------------------------- | | [ExposureMode](#exposuremode) | 获取当前曝光模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1352,6 +1613,14 @@ setExposureMode(aeMode: ExposureMode): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1377,6 +1646,14 @@ getMeteringPoint(): Point | ---------- | ----------------------------- | | [Point](#point) | 获取当前曝光点。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1411,6 +1688,14 @@ setMeteringPoint(point: Point): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1437,6 +1722,14 @@ getExposureBiasRange(): Array | ---------- | ----------------------------- | | Array | 获取补偿范围的数组。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1464,6 +1757,14 @@ setExposureBias(exposureBias: number): void | -------- | -------------------------------| ---- | ------------------- | | exposureBias | number | 是 | 曝光补偿,getExposureBiasRange查询支持的范围,接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1490,6 +1791,14 @@ getExposureValue(): number | ---------- | ----------------------------- | | number | 获取曝光值。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1521,6 +1830,14 @@ isFocusModeSupported(afMode: FocusMode): boolean | ---------- | ----------------------------- | | boolean | 返回true表示支持该焦距模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1554,6 +1871,14 @@ setFocusMode(afMode: FocusMode): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1579,6 +1904,14 @@ getFocusMode(): FocusMode | ---------- | ----------------------------- | | [FocusMode](#focusmode) | 获取当前设备的焦距模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1613,6 +1946,14 @@ setFocusPoint(point: Point): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1639,6 +1980,14 @@ getFocusPoint(): Point | ---------- | ----------------------------- | | [Point](#point) | 用于获取当前焦点。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1664,6 +2013,14 @@ getFocalLength(): number | ---------- | ----------------------------- | | number | 用于获取当前焦距。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1689,6 +2046,14 @@ getZoomRatioRange(): Array | ---------- | ----------------------------- | | Array | 用于获取可变焦距比范围,返回的数组包括其最小值和最大值。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1720,6 +2085,14 @@ setZoomRatio(zoomRatio: number): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1746,6 +2119,14 @@ getZoomRatio(): number | ---------- | ----------------------------- | | number | 获取当前的变焦比结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1777,6 +2158,14 @@ isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean | ---------- | ----------------------------- | | boolean | 返回视频防抖模式是否支持。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1802,6 +2191,14 @@ getActiveVideoStabilizationMode(): VideoStabilizationMode | ---------- | ----------------------------- | | VideoStabilizationMode | 视频防抖是否正在使用。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1833,6 +2230,14 @@ setVideoStabilizationMode(mode: VideoStabilizationMode): void | ---------- | ----------------------------- | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1912,6 +2317,14 @@ start(callback: AsyncCallback): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -1938,6 +2351,14 @@ start(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode)| +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -2012,6 +2433,14 @@ release(callback: AsyncCallback): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2038,6 +2467,14 @@ release(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2186,6 +2623,15 @@ capture(callback: AsyncCallback): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2212,6 +2658,15 @@ capture(): Promise | -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2237,6 +2692,16 @@ capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void | setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2280,6 +2745,15 @@ capture(setting?: PhotoCaptureSetting): Promise | -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | Session not running. | +| 7400201 | Camera service fatal error. | **示例:** @@ -2325,6 +2799,14 @@ release(callback: AsyncCallback): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2351,6 +2833,14 @@ release(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2495,6 +2985,15 @@ start(callback: AsyncCallback): void | -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2521,6 +3020,14 @@ start(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | **示例:** @@ -2596,6 +3103,14 @@ release(callback: AsyncCallback): void | -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2622,6 +3137,14 @@ release(): Promise | -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2719,6 +3242,15 @@ start(callback: AsyncCallback): void | -------- | -------------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **示例:** ```js @@ -2745,6 +3277,15 @@ start(): Promise | ---------------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) | +**错误码:** + +以下错误码的详细介绍请参见相机错误码 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | +| 7400201 | Camera service fatal error. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-cert.md b/zh-cn/application-dev/reference/apis/js-apis-cert.md index 8ee8bd2309e88546bc98bdb344d8e2757f86bfac..c3451703a6d58475333c37600fa88556b627bedb 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-cert.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cert.md @@ -104,6 +104,11 @@ createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : v | inStream | [EncodingBlob](#encodingblob) | 是 | X509证书序列化数据 | | callback | AsyncCallback\ | 是 | 回调函数。表示X509证书对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 19020001 | memory error. | **示例:** @@ -146,6 +151,12 @@ createX509Cert(inStream : EncodingBlob) : Promise\ | ------- | ---------------- | | Promise\ | 表示X509证书对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 19020001 | memory error. | + **示例:** ```js @@ -184,6 +195,11 @@ verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | key | cryptoFramework.PubKey | 是 | 用于验签的公钥对象 | | callback | AsyncCallback\ | 是 | 回调函数。使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,不为null表示失败 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------ | +| 19030001 | crypto operation error. | **示例:** @@ -235,6 +251,12 @@ verify(key : cryptoFramework.PubKey) : Promise\ | -------------- | ----------- | | Promise\ | Promise对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------ | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -275,6 +297,13 @@ getEncoded(callback : AsyncCallback\) : void | -------- | --------------------------------------------- | ---- | -------------------------------- | | callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | 是 | 回调函数。表示X509证书序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **示例:** @@ -318,6 +347,14 @@ getEncoded() : Promise\ | --------------------------------------- | ---------------------- | | Promise\<[EncodingBlob](#encodingblob)> | 表示X509证书序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -356,6 +393,13 @@ getPublicKey() : cryptoFramework.PubKey | ------ | ---------------- | | cryptoFramework.PubKey | X509证书公钥对象:仅用于X509Cert的verify接口 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -398,6 +442,15 @@ checkValidityWithDate(date: string) : void | -------- | -------------- | ---- | ---------- | | date | string | 是 | 日期(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间必须以Z结尾:表示标准时间) | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error.| +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired.| + **示例:** ```js @@ -513,6 +566,14 @@ getIssuerName() : DataBlob | --------------------- | ---------------------- | | [DataBlob](#datablob) | 表示X509证书颁发者名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -549,6 +610,14 @@ getSubjectName() : DataBlob | --------------------- | -------------------- | | [DataBlob](#datablob) | 表示X509证书主体名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -585,6 +654,14 @@ getNotBeforeTime() : string | ------ | ------------------------------------------------------------ | | string | 表示X509证书有效期起始时间(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间以Z结尾:表示标准时间) | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -621,6 +698,14 @@ getNotAfterTime() : string | ------ | ------------------------------------------------------------ | | string | 表示X509证书有效期截止时间(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间以Z结尾:表示标准时间) | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -657,6 +742,14 @@ getSignature() : DataBlob | --------------------- | -------------------- | | [DataBlob](#datablob) | 表示X509证书签名数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -693,6 +786,14 @@ getSignatureAlgName() : string | ------ | ------------------------ | | string | 表示X509证书签名算法名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -729,6 +830,14 @@ getSignatureAlgOid() : string | ------ | --------------------------------- | | string | 表示X509证书签名算法对象标志符OID | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -765,6 +874,14 @@ getSignatureAlgParams() : DataBlob | --------------------- | ------------------------ | | [DataBlob](#datablob) | 表示X509证书签名算法参数 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -801,6 +918,13 @@ getKeyUsage() : DataBlob | --------------------- | -------------------- | | [DataBlob](#datablob) | 表示X509证书秘钥用途 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -837,6 +961,14 @@ getExtKeyUsage() : DataArray | ----------------------- | ------------------------ | | [DataArray](#dataarray) | 表示X509证书扩展秘钥用途 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -909,6 +1041,14 @@ getSubjectAltNames() : DataArray | ----------------------- | ------------------------ | | [DataArray](#dataarray) | 表示X509证书主体可选名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -945,6 +1085,14 @@ getIssuerAltNames() : DataArray | ----------------------- | -------------------------- | | [DataArray](#dataarray) | 表示X509证书颁发者可选名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| + **示例:** ```js @@ -982,6 +1130,11 @@ createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : voi | inStream | [EncodingBlob](#encodingblob) | 是 | 表示证书吊销列表序列化数据 | | callback | AsyncCallback\ | 是 | 回调函数。表示证书吊销列表对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 19020001 | memory error. | **示例:** @@ -1024,6 +1177,12 @@ createX509Crl(inStream : EncodingBlob) : Promise\ | ----------------- | -------------------- | | Promise\ | 表示证书吊销列表对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 19020001 | memory error. | + **示例:** ```js @@ -1145,6 +1304,13 @@ getEncoded(callback : AsyncCallback\) : void | -------- | ---------------------------- | ---- | ------------------------------------------ | | callback | AsyncCallback\ | 是 | 回调函数,表示X509证书吊销列表的序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **示例:** @@ -1188,6 +1354,14 @@ getEncoded() : Promise\ | ---------------------- | -------------------------------- | | Promise\ | 表示X509证书吊销列表的序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1227,6 +1401,11 @@ verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | key | cryptoFramework.PubKey | 是 | 表示用于验签的公钥对象 | | callback | AsyncCallback\ | 是 | 回调函数,使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,error不为null表示失败。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19030001 | crypto operation error. | **示例:** @@ -1279,6 +1458,12 @@ verify(key : cryptoFramework.PubKey) : Promise\ | ---- | ------------------------------------------------------------ | | Promise\ | Promise对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1356,6 +1541,14 @@ getIssuerName() : DataBlob | --------------------- | ------------------------------ | | [DataBlob](#datablob) | 表示X509证书吊销列表颁发者名称 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1392,6 +1585,14 @@ getLastUpdate() : string | ------ | ------------------------------------ | | string | 表示X509证书吊销列表最后一次更新日期 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1428,6 +1629,14 @@ getNextUpdate() : string | ------ | ------------------------------------ | | string | 表示X509证书吊销列表下一次更新的日期 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1470,6 +1679,13 @@ getRevokedCert(serialNumber : number) : X509CrlEntry | ---------------------- | --------------------- | | X509CrlEntry | 表示被吊销X509证书对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1518,6 +1734,13 @@ getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry | ------------ | -------------------- | | X509CrlEntry | 表示被吊销X509证书对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1560,6 +1783,12 @@ getRevokedCerts(callback : AsyncCallback>) : void | -------- | ----------------------------------- | ---- | -------------------------------- | | callback | AsyncCallback> | 是 | 回调函数。表示被吊销X509证书列表 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | **示例:** @@ -1603,6 +1832,13 @@ getRevokedCerts() : Promise> | ----------------------------- | ---------------------- | | Promise> | 表示被吊销X509证书列表 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1641,6 +1877,14 @@ getTbsInfo() : DataBlob | --------------------- | ------------------------------- | | [DataBlob](#datablob) | 表示证书吊销列表的tbsCertList信息 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1681,6 +1925,14 @@ getSignature() : DataBlob | --------------------- | ------------------------------ | | [DataBlob](#datablob) | 表示X509证书吊销列表的签名数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1717,6 +1969,14 @@ getSignatureAlgName() : string | ------ | -------------------------------- | | string | 表示X509证书吊销列表签名的算法名 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1753,6 +2013,14 @@ getSignatureAlgOid() : string | ------ | --------------------------------------------- | | string | 表示X509证书吊销列表签名算法的对象标志符OID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1789,6 +2057,14 @@ getSignatureAlgParams() : DataBlob | --------------------- | ---------------------------------- | | [DataBlob](#datablob) | 表示X509证书吊销列表签名的算法参数 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1831,6 +2107,14 @@ createCertChainValidator(algorithm :string) : CertChainValidator | ------------------ | -------------------- | | CertChainValidator | 表示证书链校验器对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -1846,7 +2130,7 @@ let validator = cryptoCert.createCertChainValidator("PKIX"); ### 属性 -**系统能力:** SystemCapability.Security.CryptoFramework +**系统能力:** SystemCapability.Security.Cert | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | ------ | ---- | ---- | -------------------------- | @@ -1869,6 +2153,19 @@ validate(certChain : CertChainData, callback : AsyncCallback\) : void | certChain | [CertChainData](#certchaindata) | 是 | 表示X509证书链序列化数据 | | callback | AsyncCallback\ | 是 | 回调函数。使用AsyncCallback的第一个error参数判断是否校验成功,error为null表示成功,error不为null表示失败 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | +| 19030002 | the certificate signature verification failed. | +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired. | +| 19030005 | failed to obtain the certificate issuer. | +| 19030006 | the key cannot be used for signing a certificate. | +| 19030007 | the key cannot be used for digital signature. | **示例:** @@ -1916,6 +2213,20 @@ validate(certChain : CertChainData) : Promise\ | -------------- | ----------- | | Promise\ | Promise对象 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | +| 19030002 | the certificate signature verification failed. | +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired. | +| 19030005 | failed to obtain the certificate issuer. | +| 19030006 | the key cannot be used for signing a certificate. | +| 19030007 | the key cannot be used for digital signature. | + **示例:** ```js @@ -1980,6 +2291,13 @@ getEncoded(callback : AsyncCallback\) : void | -------- | --------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | 是 | 回调函数。表示被吊销证书的序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **示例:** @@ -2011,6 +2329,14 @@ getEncoded() : Promise\ | --------------------------------------- | -------------------------- | | Promise\<[EncodingBlob](#encodingblob)> | 表示被吊销证书的序列化数据 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js @@ -2063,6 +2389,13 @@ getCertIssuer() : DataBlob | --------------------- | ----------------------- | | [DataBlob](#datablob) | 表示被吊销证书的颁发者信息 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | + **示例:** ```js @@ -2091,6 +2424,14 @@ getRevocationDate() : string | ------ | ------------------ | | string | 表示证书被吊销的日期 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + **示例:** ```js 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 6bb571dc95c24ed6e728b5006cd4b3d33281e8a6..cac5176ad0112516fbcc559094b04bc629dacdef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -67,7 +67,7 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---------------------- | | event | string | 是 | 表示要发布的公共事件。 | -| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | 是 | 表示发布公共事件的属性。 | | callback | syncCallback\ | 是 | 表示被指定的回调方法。 | **示例:** @@ -151,7 +151,7 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca | -------- | ---------------------- | ---- | ---------------------- | | event | string | 是 | 表示要发布的公共事件。 | | userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | -| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | 是 | 表示发布公共事件的属性。 | | callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | **示例:** @@ -194,8 +194,8 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac | 参数名 | 类型 | 必填 | 说明 | | ------------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | -| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | 是 | 表示创建订阅者的回调方法。 | +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | 是 | 表示订阅信息。 | +| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | 是 | 表示创建订阅者的回调方法。 | **示例:** @@ -236,12 +236,12 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise | 返回订阅者对象。 | +| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | 返回订阅者对象。 | **示例:** @@ -276,8 +276,8 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback | 是 | 表示接收公共事件数据的回调函数。 | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | 是 | 表示接收公共事件数据的回调函数。 | **示例:** @@ -299,11 +299,12 @@ function subscribeCB(err, data) { } // 创建订阅者回调 -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); + subscriber = commonEventSubscriber; // 订阅公共事件 CommonEvent.subscribe(subscriber, subscribeCB); } @@ -327,7 +328,7 @@ unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------------------------------------- | ---- | ------------------------ | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | 是 | 表示订阅者对象。 | | callback | AsyncCallback\ | 否 | 表示取消订阅的回调方法。 | **示例:** @@ -375,809 +376,4 @@ CommonEvent.createSubscriber(subscribeInfo, createCB); // 取消订阅公共事件 CommonEvent.unsubscribe(subscriber, unsubscribeCB); -``` - -## CommonEventSubscriber - -### getCode - -```ts -getCode(callback: AsyncCallback): void -``` - -以回调形式获取公共事件代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | 是 | 公共事件代码。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取有序公共事件的结果代码回调 -function getCodeCB(err, Code) { - if (err.code) { - console.error(`getCode failed, code is ${err.code}`); - } else { - console.info("getCode " + JSON.stringify(Code)); - } -} -subscriber.getCode(getCodeCB); -``` - -### getCode - -```ts -getCode(): Promise -``` - -以Promise形式获取公共事件代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 公共事件代码。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.getCode().then((code) => { - console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { - console.error(`getCode failed, code is ${err.code}`); -}); -``` - -### setCode - -```ts -setCode(code: number, callback: AsyncCallback): void -``` - -以回调形式设置公共事件的代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | 是 | 公共事件的代码。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 设置有序公共事件的结果代码回调 -function setCodeCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}`); - } else { - console.info("setCode"); - } -} -subscriber.setCode(1, setCodeCB); -``` - -### setCode - -```ts -setCode(code: number): Promise -``` - -以Promise形式设置公共事件的代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| code | number | 是 | 公共事件的代码。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.setCode(1).then(() => { - console.info("setCode"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}`); -}); -``` - -### getData - -```ts -getData(callback: AsyncCallback): void -``` - -以回调形式获取公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 公共事件的数据。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取有序公共事件的结果数据回调 -function getDataCB(err, data) { - if (err.code) { - console.error(`getData failed, code is ${err.code}`); - } else { - console.info("getData " + JSON.stringify(data)); - } -} - -subscriber.getData(getDataCB); -``` - -### getData - -```ts -getData(): Promise -``` - -以Promise形式获取公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | ------------------ | -| Promise\ | 公共事件的数据。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.getData().then((data) => { - console.info("getData " + JSON.stringify(data)); -}).catch((err) => { - console.error(`getData failed, code is ${err.code}`); -}); -``` - -### setData - -```ts -setData(data: string, callback: AsyncCallback): void -``` - -以回调形式设置公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| data | string | 是 | 公共事件的数据。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 设置有序公共事件的结果数据回调 -function setDataCB(err) { - if (err.code) { - console.error(`sendData failed, code is ${err.code}`); - } else { - console.info("setData"); - } -} -subscriber.setData("publish_data_changed", setDataCB); -``` - -### setData - -```ts -setData(data: string): Promise -``` - -以Promise形式设置公共事件的果数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | -------------------- | -| data | string | 是 | 公共事件的数据。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.setData("publish_data_changed").then(() => { - console.info("setData"); -}).catch((err) => { - console.error(`setData failed, code is ${err.code}`); -}); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string, callback:AsyncCallback): void -``` - -以回调形式设置公共事件代码和数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | 是 | 公共事件的代码。 | -| data | string | 是 | 公共事件的数据。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 设置有序公共事件的结果代码和结果数据回调 -function setCodeDataCB(err) { - if (err.code) { - console.error(`setCodeAndData failed, code is ${err.code}`); - } else { - console.info("setCodeDataCallback"); - } -} - -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string): Promise -``` - -以Promise形式设置公共事件的代码和数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | -------------------- | -| code | number | 是 | 公共事件的代码。 | -| data | string | 是 | 公共事件的数据。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.setCodeAndData(1, "publish_data_changed").then(() => { - console.info("setCodeAndData"); -}).catch((err) => { - console.error(`setCodeAndData failed, code is ${err.code}`); -}); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(callback: AsyncCallback): void -``` - -以回调形式查询当前公共事件的是否为有序公共事件。 - -返回true代表是有序公共事件,false代表不是有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 当前公共事件的是否为有序公共事件。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取当前公共事件是否为有序事件的回调 -function isOrderedCB(err, isOrdered) { - if (err.code) { - console.error(`isOrderedCommonEvent failed, code is ${err.code}`); - } else { - console.info("isOrdered " + JSON.stringify(isOrdered)); - } -} -subscriber.isOrderedCommonEvent(isOrderedCB); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(): Promise -``` - -以Promise形式查询当前公共事件的是否为有序公共事件。 - -返回true代表是有序公共事件,false代表不是有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | -------------------------------- | -| Promise\ | 当前公共事件的是否为有序公共事件。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.isOrderedCommonEvent().then((isOrdered) => { - console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { - console.error(`isOrderedCommonEvent failed, code is ${err.code}`); -}); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(callback: AsyncCallback): void -``` - -以回调形式检查当前公共事件是否为一个粘性事件。 - -返回true代表是粘性公共事件,false代表不是粘性公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 当前公共事件的是否为粘性公共事件。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取当前公共事件是否为粘性事件的回调 -function isStickyCB(err, isSticky) { - if (err.code) { - console.error(`isStickyCommonEvent failed, code is ${err.code}`); - } else { - console.info("isSticky " + JSON.stringify(isSticky)); - } -} -subscriber.isStickyCommonEvent(isStickyCB); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(): Promise -``` - -以Promise形式检查当前公共事件是否为一个粘性事件。 - -返回true代表是粘性公共事件,false代表不是粘性公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | -------------------------------- | -| Promise\ | 当前公共事件的是否为粘性公共事件。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.isStickyCommonEvent().then((isSticky) => { - console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { - console.error(`isSticky failed, code is ${err.code}`); -}); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式取消当前的有序公共事件,取消后,有序公共事件不再向下一个订阅者传递。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 取消当前的公共事件。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 取消当前有序公共事件的回调 -function abortCB(err) { - if (err.code) { - console.error(`abortCommonEvent failed, code is ${err.code}`); - } else { - console.info("abortCommonEvent"); - } -} - -subscriber.abortCommonEvent(abortCB); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(): Promise -``` - -以Promise形式取消当前的有序公共事件,取消后,公共事件不再向下一个订阅者传递。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.abortCommonEvent().then(() => { - console.info("abortCommonEvent"); -}).catch((err) => { - console.error(`abortCommonEvent failed, code is ${err.code}`); -}); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式清除当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 清除当前公共事件取消状态的回调 -function clearAbortCB(err) { - if (err.code) { - console.error(`clearAbortCommonEvent failed, code is ${err.code}`); - } else { - console.info("clearAbortCommonEvent"); - } -} - -subscriber.clearAbortCommonEvent(clearAbortCB); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(): Promise -``` - -以Promise形式清除当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.clearAbortCommonEvent().then(() => { - console.info("clearAbortCommonEvent"); -}).catch((err) => { - console.error(`clearAbortCommonEvent failed, code is ${err.code}`); -}); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式获取当前有序公共事件是否取消的状态。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 表示当前有序公共事件是否取消的状态。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取当前有序公共事件是否取消的回调 -function getAbortCB(err, abortEvent) { - if (err.code) { - console.error(`getAbortCommonEvent failed, code is ${err.code}`); - } else { - console.info("abortEvent " + abortEvent) - } -} - -subscriber.getAbortCommonEvent(getAbortCB); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(): Promise -``` - -以Promise形式获取当前有序公共事件是否取消的状态。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | ---------------------------------- | -| Promise\ | 表示当前有序公共事件是否取消的状态。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.getAbortCommonEvent().then((abortCommonEvent) => { - console.info("abortCommonEvent " + JSON.stringify(abortCommonEvent)); -}).catch((err) => { - console.error(`getAbortCommonEvent failed, code is ${err.code}`); -}); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(callback: AsyncCallback): void -``` - -以回调形式获取订阅者的订阅信息。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 是 | 表示订阅者的订阅信息。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 获取订阅者信息回调 -function getCB(err, subscribeInfo) { - if (err.code) { - console.error(`getSubscribeInfo failed, code is ${err.code}`); - } else { - console.info("SubscribeInfo " + JSON.stringify(subscribeInfo)); - } -} - -subscriber.getSubscribeInfo(getCB); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(): Promise -``` - -以Promise形式获取订阅者的订阅信息。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------------------ | ---------------------- | -| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 表示订阅者的订阅信息。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.getSubscribeInfo().then((subscribeInfo) => { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { - console.error(`getSubscribeInfo failed, code is ${err.code}`); -}); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(callback: AsyncCallback): void -``` - -以回调形式结束当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | 是 | 表示有序公共事件结束后的回调函数。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -// 结束当前有序公共事件的回调 -function finishCB(err) { - if (err.code) { - console.error(`finishCommonEvent failed, code is ${err.code}`); - } else { - console.info("FinishCommonEvent"); - } -} - -subscriber.finishCommonEvent(finishCB); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(): Promise -``` - -以Promise形式结束当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; // 创建成功的订阅者对象 - -subscriber.finishCommonEvent().then(() => { - console.info("FinishCommonEvent"); -}).catch((err) => { - console.error(`finishCommonEvent failed, code is ${err.code}`); -}); -``` - -## CommonEventData - -公共事件数据体。 - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | -| event | string | 是 | 否 | 表示当前接收的公共事件名称。 | -| bundleName | string | 是 | 否 | 表示Bundle名称。 | -| code | number | 是 | 否 | 表示公共事件的结果代码,用于传递int类型的数据。 | -| data | string | 是 | 否 | 表示公共事件的自定义结果数据,用于传递string类型的数据。 | -| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | - - -## CommonEventPublishData - -公共事件发送的数据体,包含公共事件内容和属性。 - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------------------- | -------------------- | ---- | ---- | ---------------------------- | -| bundleName | string | 是 | 否 | 表示Bundle名称。 | -| code | number | 是 | 否 | 表示公共事件的结果代码。 | -| data | string | 是 | 否 | 表示公共事件的自定义结果数据。 | -| subscriberPermissions | Array\ | 是 | 否 | 表示订阅者的权限。 | -| isOrdered | boolean | 是 | 否 | 表示是否是有序事件。 | -| isSticky | boolean | 是 | 否 | 表示是否是粘性事件。仅系统应用或系统服务允许发送粘性事件。 | -| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | - -## CommonEventSubscribeInfo - -订阅者信息。 - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | 是 | 否 | 表示要发送的公共事件。 | -| publisherPermission | string | 是 | 否 | 表示发布者的权限。 | -| publisherDeviceId | string | 是 | 否 | 表示设备ID,该值必须是同一ohos网络上的现有设备ID。 | -| userId | number | 是 | 否 | 表示用户ID。此参数是可选的,默认值当前用户的ID。如果指定了此参数,则该值必须是系统中现有的用户ID。 | -| priority | number | 是 | 否 | 表示订阅者的优先级。值的范围是-100到1000。 | \ No newline at end of file +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md index 8873bc0e67a8cd392da2d1c7813c9cf66fafbd26..b3bdfc02bd4ab3e0e3dd7081dcab3205f2b11dd8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @@ -74,7 +74,7 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---------------------- | | event | string | 是 | 表示要发布的公共事件。 | -| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | 是 | 表示发布公共事件的属性。 | | callback | syncCallback\ | 是 | 表示被指定的回调方法。 | **错误码:** @@ -173,7 +173,7 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca | -------- | ---------------------- | ---- | ---------------------- | | event | string | 是 | 表示要发布的公共事件。 | | userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | -| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | 是 | 表示发布公共事件的属性。 | | callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | **错误码:** @@ -224,8 +224,8 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac | 参数名 | 类型 | 必填 | 说明 | | ------------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | -| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | 是 | 表示创建订阅者的回调方法。 | +| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | 是 | 表示订阅信息。 | +| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | 是 | 表示创建订阅者的回调方法。 | **示例:** @@ -270,12 +270,12 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise | 返回订阅者对象。 | +| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | 返回订阅者对象。 | **示例:** @@ -311,8 +311,8 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback | 是 | 表示接收公共事件数据的回调函数。 | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | 是 | 表示接收公共事件数据的回调函数。 | **示例:** @@ -327,7 +327,7 @@ let subscribeInfo = { //订阅公共事件回调 function SubscribeCB(err, data) { - if (err.code) { + if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe "); @@ -335,9 +335,10 @@ function SubscribeCB(err, data) { } //创建订阅者回调 -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if(!err) { console.info("createSubscriber"); + subscriber = commonEventSubscriber; //订阅公共事件 try { CommonEventManager.subscribe(subscriber, SubscribeCB); @@ -371,7 +372,7 @@ unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------------------------------------- | ---- | ------------------------ | -| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | 是 | 表示订阅者对象。 | | callback | AsyncCallback\ | 否 | 表示取消订阅的回调方法。 | **示例:** @@ -391,11 +392,12 @@ function subscribeCB(err, data) { } } //创建订阅者回调 -function createCB(err, subscriber) { +function createCB(err, commonEventSubscriber) { if (err) { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { console.info("createSubscriber"); + subscriber = commonEventSubscriber; //订阅公共事件 try { CommonEventManager.subscribe(subscriber, subscribeCB); @@ -425,794 +427,4 @@ try { } catch (err) { console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } -``` - -## CommonEventSubscriber - -### getCode - -```ts -getCode(callback: AsyncCallback): void -``` - -以回调形式获取公共事件代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | 是 | 公共事件代码。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取有序公共事件代码回调 -function getCodeCB(err, code) { - if (err.code) { - console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("getCode " + JSON.stringify(code)); - } -} -subscriber.getCode(getCodeCB); -``` - -### getCode - -```ts -getCode(): Promise -``` - -以Promise形式获取公共事件代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 公共事件代码。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.getCode().then((code) => { - console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { - console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setCode - -```ts -setCode(code: number, callback: AsyncCallback): void -``` - -以回调形式设置公共事件的代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | 是 | 公共事件的代码。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//设置有序公共事件的代码回调 -function setCodeCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setCode"); - } -} -subscriber.setCode(1, setCodeCB); -``` - -### setCode - -```ts -setCode(code: number): Promise -``` - -以Promise形式设置公共事件的代码。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| code | number | 是 | 公共事件的代码。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.setCode(1).then(() => { - console.info("setCode"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getData - -```ts -getData(callback: AsyncCallback): void -``` - -以回调形式获取公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 公共事件的数据。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取有序公共事件代码数据回调 -function getDataCB(err, data) { - if (err.code) { - console.error(`getData failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("getData " + JSON.stringify(data)); - } -} -subscriber.getData(getDataCB); -``` - -### getData - -```ts -getData(): Promise -``` - -以Promise形式获取公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | ------------------ | -| Promise\ | 公共事件的数据。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.getData().then((data) => { - console.info("getData " + JSON.stringify(data)); -}).catch((err) => { - console.error(`getData failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setData - -setData(data: string, callback: AsyncCallback\): void - -以回调形式设置公共事件的数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| data | string | 是 | 公共事件的数据。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//设置有序公共事件的结果数据回调 -function setDataCB(err) { - if (err.code) { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setData"); - } -} -subscriber.setData("publish_data_changed", setDataCB); -``` - -### setData - -```ts -setData(data: string): Promise -``` - -以Promise形式设置公共事件的果数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | -------------------- | -| data | string | 是 | 公共事件的数据。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.setData("publish_data_changed").then(() => { - console.info("setData"); -}).catch((err) => { - console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string, callback:AsyncCallback): void -``` - -以回调形式设置公共事件代码和数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------- | -| code | number | 是 | 公共事件的代码。 | -| data | string | 是 | 公共事件的数据。 | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//设置有序公共事件的代码和数据回调 -function setCodeDataCB(err) { - if (err.code) { - console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("setCodeDataCallback"); - } -} -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); -``` - -### setCodeAndData - -```ts -setCodeAndData(code: number, data: string): Promise -``` - -以Promise形式设置公共事件的代码和数据。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | -------------------- | -| code | number | 是 | 公共事件的代码。 | -| data | string | 是 | 公共事件的数据。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.setCodeAndData(1, "publish_data_changed").then(() => { - console.info("setCodeAndData"); -}).catch((err) => { - console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(callback: AsyncCallback): void -``` - -以回调形式查询当前公共事件的是否为有序公共事件。 - -返回true代表是有序公共事件,false代表不是有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 当前公共事件的是否为有序公共事件。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取当前公共事件是否为有序事件的回调 -function isOrderedCB(err, isOrdered) { - if (err.code) { - console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("isOrdered " + JSON.stringify(isOrdered)); - } -} -subscriber.isOrderedCommonEvent(isOrderedCB); -``` - -### isOrderedCommonEvent - -```ts -isOrderedCommonEvent(): Promise -``` - -以Promise形式查询当前公共事件的是否为有序公共事件。 - -返回true代表是有序公共事件,false代表不是有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | -------------------------------- | -| Promise\ | 当前公共事件的是否为有序公共事件。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.isOrderedCommonEvent().then((isOrdered) => { - console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { - console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(callback: AsyncCallback): void -``` - -以回调形式检查当前公共事件是否为一个粘性事件。 - -返回true代表是粘性公共事件,false代表不是粘性公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 当前公共事件的是否为粘性公共事件。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取当前公共事件是否为粘性事件的回调 -function isStickyCB(err, isSticky) { - if (err.code) { - console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("isSticky " + JSON.stringify(isSticky)); - } -} -subscriber.isStickyCommonEvent(isStickyCB); -``` - -### isStickyCommonEvent - -```ts -isStickyCommonEvent(): Promise -``` - -以Promise形式检查当前公共事件是否为一个粘性事件。 - -返回true代表是粘性公共事件,false代表不是粘性公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | -------------------------------- | -| Promise\ | 当前公共事件的是否为粘性公共事件。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.isStickyCommonEvent().then((isSticky) => { - console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { - console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式取消当前的有序公共事件,取消后,有序公共事件不再向下一个订阅者传递。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 取消当前的有序公共事件。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//取消当前有序公共事件的回调 -function abortCB(err) { - if (err.code) { - console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("abortCommonEvent"); - } -} -subscriber.abortCommonEvent(abortCB); -``` - -### abortCommonEvent - -```ts -abortCommonEvent(): Promise -``` - -以Promise形式取消当前的有序公共事件,取消后,公共事件不再向下一个订阅者传递。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.abortCommonEvent().then(() => { - console.info("abortCommonEvent"); -}).catch((err) => { - console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式清除当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//清除当前公共事件取消状态的回调 -function clearAbortCB(err) { - if (err.code) { - console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("clearAbortCommonEvent"); - } -} -subscriber.clearAbortCommonEvent(clearAbortCB); -``` - -### clearAbortCommonEvent - -```ts -clearAbortCommonEvent(): Promise -``` - -以Promise形式清除当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.clearAbortCommonEvent().then(() => { - console.info("clearAbortCommonEvent"); -}).catch((err) => { - console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(callback: AsyncCallback): void -``` - -以回调形式获取当前有序公共事件是否取消的状态。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ---------------------------------- | -| callback | AsyncCallback\ | 是 | 表示当前有序公共事件是否取消的状态。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取当前有序公共事件是否取消的回调 -function getAbortCB(err, abortEvent) { - if (err.code) { - console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("abortCommonEvent " + abortEvent) - } -} -subscriber.getAbortCommonEvent(getAbortCB); -``` - -### getAbortCommonEvent - -```ts -getAbortCommonEvent(): Promise -``` - -以Promise形式获取当前有序公共事件是否取消的状态。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ----------------- | ---------------------------------- | -| Promise\ | 表示当前有序公共事件是否取消的状态。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.getAbortCommonEvent().then((abortEvent) => { - console.info("abortCommonEvent " + JSON.stringify(abortEvent)); -}).catch((err) => { - console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(callback: AsyncCallback): void -``` - -以回调形式获取订阅者的订阅信息。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 是 | 表示订阅者的订阅信息。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//获取订阅者信息回调 -function getCB(err, subscribeInfo) { - if (err.code) { - console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); - } -} -subscriber.getSubscribeInfo(getCB); -``` - -### getSubscribeInfo - -```ts -getSubscribeInfo(): Promise -``` - -以Promise形式获取订阅者的订阅信息。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------------------ | ---------------------- | -| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 表示订阅者的订阅信息。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.getSubscribeInfo().then((subscribeInfo) => { - console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { - console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(callback: AsyncCallback): void -``` - -以回调形式结束当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | 是 | 表示有序公共事件结束后的回调函数。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -//结束当前有序公共事件的回调 -function finishCB(err) { - if (err.code) { - console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); -} else { - console.info("FinishCommonEvent"); -} - -subscriber.finishCommonEvent(finishCB); -``` - -### finishCommonEvent9+ - -```ts -finishCommonEvent(): Promise -``` - -以Promise形式结束当前有序公共事件。 - -**系统能力**:`SystemCapability.Notification.CommonEvent` - -**返回值:** - -| 类型 | 说明 | -| ---------------- | -------------------- | -| Promise\ | 返回一个Promise的结果。 | - -**示例:** - -```ts -let subscriber; //创建成功的订阅者对象 - -subscriber.finishCommonEvent().then(() => { - console.info("FinishCommonEvent"); -}).catch((err) => { - console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); -}); -``` - -## CommonEventData - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | -| event | string | 是 | 否 | 表示当前接收的公共事件名称。 | -| bundleName | string | 是 | 否 | 表示包名称。 | -| code | number | 是 | 否 | 表示公共事件的结果代码,用于传递int类型的数据。 | -| data | string | 是 | 否 | 表示公共事件的自定义结果数据,用于传递string类型的数据。 | -| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | - - -## CommonEventPublishData - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------------------- | -------------------- | ---- | ---- | ---------------------------- | -| bundleName | string | 是 | 否 | 表示包名称。 | -| code | number | 是 | 否 | 表示公共事件的结果代码。 | -| data | string | 是 | 否 | 表示公共事件的自定义结果数据。 | -| subscriberPermissions | Array\ | 是 | 否 | 表示订阅者的权限。 | -| isOrdered | boolean | 是 | 否 | 表示是否是有序事件。 | -| isSticky | boolean | 是 | 否 | 表示是否是粘性事件。仅系统应用或系统服务允许发送粘性事件。 | -| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | - -## CommonEventSubscribeInfo - -**系统能力:** `SystemCapability.Notification.CommonEvent` - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | 是 | 否 | 表示要发送的公共事件。 | -| publisherPermission | string | 是 | 否 | 表示发布者的权限。 | -| publisherDeviceId | string | 是 | 否 | 表示设备ID,该值必须是同一ohos网络上的现有设备ID。 | -| userId | number | 是 | 否 | 表示用户ID。此参数是可选的,默认值当前用户的ID。如果指定了此参数,则该值必须是系统中现有的用户ID。 | -| priority | number | 是 | 否 | 表示订阅者的优先级。值的范围是-100到1000。 | \ No newline at end of file +``` \ No newline at end of file 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 ba5f0890e965eae69492c42dfc7014a059c85161..0c80adbe729fabcdff44ca7009521f8963eb2820 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -2217,6 +2217,8 @@ sign(data : DataBlob) : Promise\ | -------------- | ----------- | | Promise\ | Promise对象 | +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------- | | 17620001 | memory error. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-curve.md b/zh-cn/application-dev/reference/apis/js-apis-curve.md index 51af65f7cc9437fb90a1156ce33f1492008788a9..f3892ab6da6ca22906ad5e02042b358c7cb2d179 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-curve.md +++ b/zh-cn/application-dev/reference/apis/js-apis-curve.md @@ -209,9 +209,10 @@ Curves.responsiveSpringMotion() // 创建一个默认弹性跟手动画曲线 interpolate(fraction: number): number - 插值曲线的插值计算函数,可以通过传入的归一化时间参数返回当前的插值 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md index 5af7eba6884396c0f309b3b2b74106f3b6d6c780..a44d2d568b7c9e8f202b5318cb9d869a3da953f0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -363,7 +363,12 @@ save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void ```ts g_object.setSessionId("123456"); -g_object.save("local", (result) => { +g_object.save("local", (err, result) => { + if (err) { + console.info("save failed, error code = " + err.code); + console.info("save failed, error message: " + err.message); + return; + } console.info("save callback"); console.info("save sessionId: " + result.sessionId); console.info("save version: " + result.version); @@ -408,8 +413,9 @@ g_object.save("local").then((result) => { console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}, () => { - console.error("save failed"); +}).catch((err) => { + console.info("save failed, error code = " + err.code); + console.info("save failed, error message: " + err.message); }); ``` @@ -435,16 +441,26 @@ revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void ```js g_object.setSessionId("123456"); // 持久化数据 -g_object.save("local", (result) => { +g_object.save("local", (err, result) => { + if (err) { + console.info("save failed, error code = " + err.code); + console.info("save failed, error message: " + err.message); + return; + } console.info("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); + console.info("save sessionId: " + result.sessionId); + console.info("save version: " + result.version); + console.info("save deviceId: " + result.deviceId); }); // 删除持久化保存的数据 -g_object.revokeSave((result) => { - console.info("revokeSave callback"); - console.info("revokeSave sessionId " + result.sessionId); +g_object.revokeSave((err, result) => { + if (err) { + console.info("revokeSave failed, error code = " + err.code); + console.info("revokeSave failed, error message: " + err.message); + return; + } + console.info("revokeSave callback"); + console.info("revokeSave sessionId " + result.sessionId); }); ``` @@ -475,15 +491,17 @@ g_object.save("local").then((result) => { console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}, () => { - console.error("save failed"); +}).catch((err) => { + console.info("save failed, error code = " + err.code); + console.info("save failed, error message: " + err.message); }); // 删除持久化保存的数据 g_object.revokeSave().then((result) => { console.info("revokeSave callback"); console.info("sessionId" + result.sessionId); -}, () => { - console.error("revokeSave failed"); +}).catch((err)=> { + console.info("revokeSave failed, error code = " + err.code); + console.info("revokeSave failed, error message = " + err.message); }); ``` @@ -583,7 +601,7 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri **示例:** ```js -import distributedObject from '@ohos.data.distributedDataObject'; +import distributedObject from '@ohos.data.distributedDataObject'; let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.changeCallback = (sessionId, changeData) => { console.info("change" + sessionId); @@ -619,7 +637,7 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st **示例:** ```js -import distributedObject from '@ohos.data.distributedDataObject'; +import distributedObject from '@ohos.data.distributedDataObject'; let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // 删除数据变更回调changeCallback g_object.off("change", globalThis.changeCallback); @@ -680,7 +698,7 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s **示例:** ```js -import distributedObject from '@ohos.data.distributedDataObject'; +import distributedObject from '@ohos.data.distributedDataObject'; let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index 28ab08ee63ca43fe7e34fce781ee3ba8282241b3..12c7ff4f5e0fa234c19ac6dc05b65e5b468f94ed 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -31,7 +31,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number, callback: As | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-app-context.md)。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | version | number | 是 | 数据库版本。
目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | | callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | @@ -92,7 +92,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number): Promise< | 参数名 | 类型 | 必填 | 说明 | | ------- | --------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-app-context.md)。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | version | number | 是 | 数据库版本。
目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | @@ -156,7 +156,7 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-app-context.md)。 | | name | string | 是 | 数据库名称。 | | callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | @@ -214,7 +214,7 @@ deleteRdbStore(context: Context, name: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-app-context.md)。 | | name | string | 是 | 数据库名称。 | **返回值**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md index 4c94720c13746c8a1ff26203755b29a34106a649..564bde75b6d087feca5e8945eab230ad6551e372 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -30,7 +30,7 @@ getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<Rd | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | @@ -108,7 +108,7 @@ getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | 参数名 | 类型 | 必填 | 说明 | | ------- | -------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | **返回值**: @@ -188,7 +188,7 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | | name | string | 是 | 数据库名称。 | | callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | @@ -249,7 +249,7 @@ deleteRdbStore(context: Context, name: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | | name | string | 是 | 数据库名称。 | **返回值**: @@ -2612,9 +2612,9 @@ store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, r let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(['12345678abcde']); let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); -promise.then((resultSet) =>{ +promise.then((result) =>{ console.info(`Sync done.`); - for (let i = 0; i < resultSet.length; i++) { + for (let i = 0; i < result.length; i++) { console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); } }).catch((err) => { @@ -2693,10 +2693,12 @@ try { 首先需要获取resultSet对象。 ```js +let resultSet = null; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("AGE", 18); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((result) => { + resultSet = result; console.info(`resultSet columnNames: ${resultSet.columnNames}`); console.info(`resultSet columnCount: ${resultSet.columnCount}`); }); @@ -2867,7 +2869,7 @@ goToRow(position: number): boolean let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.(5); + resultSet.goToRow(5); resultSet.close(); }).catch((err) => { console.error(`query failed, err: ${err}`); diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md index 83f6e63572daa8b30d9decfa8a8e1131609c11ba..3c0701bd503245342420ea3cefb2f849d8b87ab6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md @@ -96,7 +96,7 @@ createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager | CAR | 0x83 | 车 | | UNKNOWN_TYPE | 0 | 未知设备 | -## AuthForm +## AuthForm10+ 表示设备认证类型的枚举类。 @@ -262,8 +262,6 @@ getTrustedDeviceListSync(): Array<DeviceInfo> 同步获取所有可信设备列表。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **返回值:** @@ -296,8 +294,6 @@ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): voi 获取所有可信设备列表。使用callback异步回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -336,8 +332,6 @@ getTrustedDeviceList(): Promise<Array<DeviceInfo>> 获取所有可信设备列表。使用Promise异步回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **返回值:** @@ -370,8 +364,6 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) 同步获取本地设备信息。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **返回值:** @@ -404,8 +396,6 @@ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void 获取本地设备信息。使用callback异步回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -444,8 +434,6 @@ getLocalDeviceInfo(): Promise<DeviceInfo> 获取本地设备信息。使用Promise异步回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **返回值:** @@ -478,8 +466,6 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo): void 发现周边设备。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -524,8 +510,6 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void 发现周边设备。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -580,8 +564,6 @@ stopDeviceDiscovery(subscribeId: number): void 停止发现周边设备。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -616,8 +598,6 @@ publishDeviceDiscovery(publishInfo: PublishInfo): void 发布设备发现。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -659,8 +639,6 @@ unPublishDeviceDiscovery(publishId: number): void 停止发布设备发现。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -695,8 +673,6 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async 认证设备。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -757,8 +733,6 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void 解除认证设备。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -798,8 +772,6 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, 验证认证信息。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -844,8 +816,6 @@ setUserOperation(operateAction: number, params: string): void; 设置用户ui操作行为。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -880,8 +850,6 @@ requestCredentialRegisterInfo(requestInfo: string, callback: AsyncCallback<{regi 获取凭据的注册信息。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -917,8 +885,6 @@ importCredential(credentialInfo: string, callback: AsyncCallback<{resultInfo: st 导入凭据信息。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -970,8 +936,6 @@ deleteCredential(queryInfo: string, callback: AsyncCallback<{resultInfo: string} 删除凭据信息。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1008,8 +972,6 @@ on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; ui状态变更回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1040,8 +1002,6 @@ off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; 取消ui状态变更回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1067,8 +1027,6 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange 注册设备状态回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1096,8 +1054,6 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang 取消注册设备状态回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1125,8 +1081,6 @@ on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: Dev 注册发现设备回调监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1154,8 +1108,6 @@ off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: D 取消注册设备发现回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1183,8 +1135,6 @@ on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: nu 注册设备发现失败回调监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1212,8 +1162,6 @@ off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: 取消注册设备发现失败回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1241,8 +1189,6 @@ on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): voi 注册发布设备发现回调监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1271,8 +1217,6 @@ off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): v 取消注册设备发布成功回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1300,8 +1244,6 @@ on(type: 'publishFail', callback: Callback<{ publishId: number, reason: numbe 注册设备发布失败回调监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1329,8 +1271,6 @@ off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: num 取消注册设备发布失败回调。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1358,8 +1298,6 @@ on(type: 'serviceDie', callback: () => void): void 注册设备管理服务死亡监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** @@ -1387,8 +1325,6 @@ off(type: 'serviceDie', callback?: () => void): void 取消注册设备管理服务死亡监听。 -**需要权限**:ohos.permission.ACCESS_SERVICE_DM,仅系统应用可用。 - **系统能力**:SystemCapability.DistributedHardware.DeviceManager **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index 385251bb566383c332c8f10952191ef7121674f7..1cade67ddc4d97371f9c07925a508a6195293efe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -43,7 +43,7 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **参数:** @@ -79,7 +79,7 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **返回值:** @@ -118,7 +118,7 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **参数:** @@ -148,7 +148,7 @@ queryOsAccountDistributedInfo(): Promise<DistributedInfo> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **返回值:** @@ -175,7 +175,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS **参数:** @@ -213,7 +213,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS **参数:** @@ -260,7 +260,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS **参数:** @@ -288,7 +288,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> > 从 API version 7开始支持,从API version 9开始废弃。建议使用[setOsAccountDistributedInfo](#setosaccountdistributedinfo9-1)。 **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md index 3b61f968c98f5bd3ac708e912b8f39e7f776a029..84206aabcfe16da05849f39ad6f308eda9db28b8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -28,7 +28,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; | 名称 | 类型 | 必填 | 说明 | | ---------- | --------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | | bundleName | string | 是 | 调用方的包名。 | ## Constants @@ -1242,7 +1242,7 @@ reset(): Query | 类型 | 说明 | | -------------- | --------------------- | -| [Query](query) | 返回重置的Query对象。 | +| [Query](#query) | 返回重置的Query对象。 | **示例:** @@ -1278,7 +1278,7 @@ equalTo(field: string, value: number|string|boolean): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1312,7 +1312,7 @@ notEqualTo(field: string, value: number|string|boolean): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1345,7 +1345,7 @@ greaterThan(field: string, value: number|string|boolean): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1380,7 +1380,7 @@ lessThan(field: string, value: number|string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1415,7 +1415,7 @@ greaterThanOrEqualTo(field: string, value: number|string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1450,7 +1450,7 @@ lessThanOrEqualTo(field: string, value: number|string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1483,7 +1483,7 @@ isNull(field: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1517,7 +1517,7 @@ inNumber(field: string, valueList: number[]): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1551,7 +1551,7 @@ inString(field: string, valueList: string[]): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1585,7 +1585,7 @@ notInNumber(field: string, valueList: number[]): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1619,7 +1619,7 @@ notInString(field: string, valueList: string[]): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1653,7 +1653,7 @@ like(field: string, value: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1687,7 +1687,7 @@ unlike(field: string, value: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1714,7 +1714,7 @@ and(): Query | 类型 | 说明 | | -------------- | -------------- | -| [Query](query) | 返回查询对象。 | +| [Query](#query) | 返回查询对象。 | **示例:** @@ -1743,7 +1743,7 @@ or(): Query | 类型 | 说明 | | -------------- | -------------- | -| [Query](query) | 返回查询对象。 | +| [Query](#query) | 返回查询对象。 | **示例:** @@ -1778,7 +1778,7 @@ orderByAsc(field: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1812,7 +1812,7 @@ orderByDesc(field: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1847,7 +1847,7 @@ limit(total: number, offset: number): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1883,7 +1883,7 @@ isNotNull(field: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1910,7 +1910,7 @@ beginGroup(): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1939,7 +1939,7 @@ endGroup(): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -1974,7 +1974,7 @@ prefixKey(prefix: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -2008,7 +2008,7 @@ setSuggestIndex(index: string): Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -2042,7 +2042,7 @@ deviceId(deviceId:string):Query | 类型 | 说明 | | -------------- | --------------- | -| [Query](query) | 返回Query对象。 | +| [Query](#query) | 返回Query对象。 | **示例:** @@ -3086,7 +3086,7 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ----------------------------------------------- | -| query | [Query](query) | 是 | 表示要匹配的键前缀。 | +| query | [Query](#query) | 是 | 表示要匹配的键前缀。 | | callback | AsyncCallback<[Entry](#entry)[]> | 是 | 回调函数。返回与指定Query对象匹配的键值对列表。 | **错误码:** @@ -3148,7 +3148,7 @@ getEntries(query: Query): Promise<Entry[]> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -3414,7 +3414,7 @@ getResultSet(query: Query): Promise<KVStoreResultSet> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -3661,7 +3661,7 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | | callback | AsyncCallback<number> | 是 | 回调函数。返回与指定Query对象匹配的结果数。 | **错误码:** @@ -3719,7 +3719,7 @@ getResultSize(query: Query): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -4548,7 +4548,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void | --------- | --------------------- | ---- | ---------------------------------------------- | | deviceIds | string[] | 是 | 同一组网环境下,需要同步的设备的deviceId列表。 | | mode | [SyncMode](#syncmode) | 是 | 同步模式。 | -| query | [Query](query) | 是 | 表示数据库的查询谓词条件 | +| query | [Query](#query) | 是 | 表示数据库的查询谓词条件 | | delayMs | number | 否 | 可选参数,允许延时时间,单位:ms(毫秒)。 | **错误码:** @@ -5324,7 +5324,7 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ----------------------------------------------------- | -| query | [Query](query) | 是 | 表示要匹配的键前缀。 | +| query | [Query](#query) | 是 | 表示要匹配的键前缀。 | | callback | AsyncCallback<[Entry](#entry)[]> | 是 | 回调函数。返回本设备与指定Query对象匹配的键值对列表。 | **错误码:** @@ -5386,7 +5386,7 @@ getEntries(query: Query): Promise<Entry[]> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -5453,7 +5453,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ------------------------------------------------------- | | deviceId | string | 是 | 键值对所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | | callback | AsyncCallback<[Entry](#entry)[]> | 是 | 回调函数。返回与指定设备ID和Query对象匹配的键值对列表。 | **错误码:** @@ -5522,7 +5522,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | -------------------- | | deviceId | string | 是 | 键值对所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -5830,7 +5830,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | | callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | 是 | 回调函数。返回与指定设备ID和Query对象匹配的KVStoreResultSet对象。 | **错误码:** @@ -5902,7 +5902,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -5975,7 +5975,7 @@ getResultSet(query: Query): Promise<KVStoreResultSet> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -6041,7 +6041,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -6341,7 +6341,7 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------------------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | | callback | AsyncCallback<number> | 是 | 回调函数。返回与本设备指定Query对象匹配的结果数。 | **错误码:** @@ -6399,7 +6399,7 @@ getResultSize(query: Query): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** @@ -6463,7 +6463,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------------------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | | callback | AsyncCallback<number> | 是 | 回调函数。返回与指定设备ID和Query对象匹配的结果数。 | **错误码:** @@ -6527,7 +6527,7 @@ getResultSize(deviceId: string, query: Query): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | -| query | [Query](query) | 是 | 表示查询对象。 | +| query | [Query](#query) | 是 | 表示查询对象。 | **返回值:** 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 ca314eff605dd2044ddc27603fad7d937747b526..d346ef568f3ba995f77b8c2b2a7adccc65ec73bb 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -368,8 +368,8 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callba | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------- | ---- | ----- | -| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | 是 | 迁移信息。 | -| options | [ContinueCallback](#continuecallback) | 是 | 迁移任务完成回调函数。 | +| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | 是 | 迁移信息。 | +| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | 是 | 迁移任务完成回调函数。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | **错误码:** @@ -426,8 +426,8 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promi | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------- | ---- | ----- | -| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | 是 | 迁移信息。 | -| options | [ContinueCallback](#continuecallback) | 是 | 迁移任务完成回调函数。 | +| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | 是 | 迁移信息。 | +| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | 是 | 迁移任务完成回调函数。 | **返回值:** @@ -513,31 +513,4 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promi | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | ------ | ---- | ---- | ------- | -| deviceId | string | 是 | 是 | 表示设备ID。 | - -## ContinueDeviceInfo - -表示发起任务迁移时所需参数的枚举。 - -**需要权限**:ohos.permission.MANAGE_MISSIONS - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | ------ | ---- | ---- | ------- | -| srcDeviceId | string | 是 | 是 | 表示任务迁移源设备ID。 | -| dstDeviceId | string | 是 | 是 | 表示任务迁移目标设备ID。 | -| missionId | number | 是 | 是 | 表示任务ID。 | -| wantParam | {[key: string]: any} | 是 | 是 | 表示扩展参数。 | - -## ContinueCallback - -表示迁移完成后,返回迁移结果回调函数。 - -**需要权限**:ohos.permission.MANAGE_MISSIONS - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------------------- | -------- | ---- | ---- | ------------------ | -| onContinueDone | function | 是 | 否 | 通知迁移完成,返回迁移结果。 | \ No newline at end of file +| deviceId | string | 是 | 是 | 表示设备ID。 | \ No newline at end of file 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 64187e6a825c930ddadbd4cfa75401d1ecac1ea8..c77ef0bc116f020640db7c0d920bbb82c409867d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-emitter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-emitter.md @@ -161,4 +161,4 @@ emitter.emit(innerEvent, eventData); | 名称 | 类型 | 可读 | 可写 | 说明 | | ---- | ------------------ | ---- | ---- | -------------- | -| data | [key: string]: any | 是 | 是 | 发送事件时传递的数据,数据类型支持字符串、整型和布尔型。 | +| data | [key: string]: any | 是 | 是 | 发送事件时传递的数据,数据类型支持字符串、整型和布尔型。
其中字符串长度最大为10240字节。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md index 81dbd16db9c033e8ce5dffa52fcc2db355336b7c..9f90c727a1a72638a10ee0a416ae6a5e5d843918 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @@ -60,7 +60,7 @@ wifiManager.isWifiActive(wantTemp, (error, result) => { isWifiActive(admin: Want): Promise<boolean> -获取wifi开启状态,使用callback形式返回wifi开启状态。 +获取wifi开启状态,使用promise形式返回wifi开启状态。 **需要权限:** ohos.permission.ENTERPRISE_SET_WIFI 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 4d23dcbbf40b40346096ff71db83443c53911676..c403de289f98a680174bef93c5392adc47d3909f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md +++ b/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @@ -40,11 +40,9 @@ import faultLogger from '@ohos.faultLogger' | summary | string | 是 | 故障的概要 | | fullLog | string | 是 | 故障日志全文 | -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +## faultLogger.query9+ -> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9)替代。 +query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void 获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -57,6 +55,14 @@ querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<Faul | faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | 是 | 回调函数,在回调函数中获取故障信息数组。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常,error返回错误提示字符串 +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息 | +| --- | --- | +| 10600001 | The service is not started or is faulty | + **示例:** ```js @@ -79,14 +85,16 @@ function queryFaultLogCallback(error, value) { } } } -faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +try { + faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +} catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} ``` -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> +## faultLogger.query9+ -> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9-1)替代。 +query(faultType: FaultType) : Promise<Array<FaultLogInfo>> 获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -104,32 +112,48 @@ querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>&g | -------- | -------- | | Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise实例,可以在其then()方法中获取故障信息实例,也可以使用await。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常 | +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息 | +| --- | --- | +| 10600001 | The service is not started or is faulty | + **示例:** ```js 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); + 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}`); } } ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void + +> **说明:** +> +> 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9)替代。 获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -142,14 +166,6 @@ query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo> | faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | 是 | 回调函数,在回调函数中获取故障信息数组。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常,error返回错误提示字符串 -**错误码:** - -以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 - -| 错误码ID | 错误信息 | -| --- | --- | -| 10600001 | The service is not running or broken | - **示例:** ```js @@ -172,16 +188,16 @@ function queryFaultLogCallback(error, value) { } } } -try { - faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); -} catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); -} +faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType) : Promise<Array<FaultLogInfo>> +querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> + +> **说明:** +> +> 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9-1)替代。 获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -199,37 +215,25 @@ query(faultType: FaultType) : Promise<Array<FaultLogInfo>> | -------- | -------- | | 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); - } + 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); } - } catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); } } -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md index 9bb182ad56fd974c080cf006f1ed7819b96da131..9bc6e12e371d0c6f1517870fc8b3a6589dddd224 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md @@ -65,7 +65,7 @@ stat(file: string|number): Promise<Stat> **示例:** ```js - let filePath = pathDir + "test.txt"; + let filePath = pathDir + "/test.txt"; fs.stat(filePath).then((stat) => { console.info("get file info succeed, the size of file is " + stat.size); }).catch((err) => { @@ -330,8 +330,8 @@ copyFile(src: string|number, dest: string|number, mode?: number): Promise<voi **示例:** ```js - let srcPath = pathDir + "srcDir/test.txt"; - let dstPath = pathDir + "dstDir/test.txt"; + let srcPath = pathDir + "/srcDir/test.txt"; + let dstPath = pathDir + "/dstDir/test.txt"; fs.copyFile(srcPath, dstPath).then(() => { console.info("copy file succeed"); }).catch((err) => { @@ -359,8 +359,8 @@ copyFile(src: string|number, dest: string|number, mode?: number, callback: Async **示例:** ```js - let srcPath = pathDir + "srcDir/test.txt"; - let dstPath = pathDir + "dstDir/test.txt"; + let srcPath = pathDir + "/srcDir/test.txt"; + let dstPath = pathDir + "/dstDir/test.txt"; fs.copyFile(srcPath, dstPath, (err) => { if (err) { console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); @@ -390,8 +390,8 @@ copyFileSync(src: string|number, dest: string|number, mode?: number): void **示例:** ```js - let srcPath = pathDir + "srcDir/test.txt"; - let dstPath = pathDir + "dstDir/test.txt"; + let srcPath = pathDir + "/srcDir/test.txt"; + let dstPath = pathDir + "/dstDir/test.txt"; fs.copyFileSync(srcPath, dstPath); ``` @@ -419,7 +419,7 @@ mkdir(path: string): Promise<void> **示例:** ```js - let dirPath = pathDir + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.mkdir(dirPath).then(() => { console.info("mkdir succeed"); }).catch((err) => { @@ -446,7 +446,7 @@ mkdir(path: string, callback: AsyncCallback<void>): void **示例:** ```js - let dirPath = pathDir + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.mkdir(dirPath, (err) => { if (err) { console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); @@ -474,7 +474,7 @@ mkdirSync(path: string): void **示例:** ```js - let dirPath = path + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.mkdirSync(dirPath); ``` @@ -600,7 +600,7 @@ read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: numb let buf = new ArrayBuffer(4096); fs.read(file.fd, buf).then((readLen) => { console.info("read file data succeed"); - console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); fs.closeSync(file); }).catch((err) => { console.info("read file data failed with error message: " + err.message + ", error code: " + err.code); @@ -635,7 +635,7 @@ read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: numb console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("read file data succeed"); - console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); fs.closeSync(file); } }); @@ -698,7 +698,7 @@ rmdir(path: string): Promise<void> **示例:** ```js - let dirPath = pathDir + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.rmdir(dirPath).then(() => { console.info("rmdir succeed"); }).catch((err) => { @@ -725,7 +725,7 @@ rmdir(path: string, callback: AsyncCallback<void>): void **示例:** ```js - let dirPath = pathDir + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.rmdir(dirPath, (err) => { if (err) { console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); @@ -753,7 +753,7 @@ rmdirSync(path: string): void **示例:** ```js - let dirPath = pathDir + '/testDir'; + let dirPath = pathDir + "/testDir"; fs.rmdirSync(dirPath); ``` @@ -1235,7 +1235,7 @@ rename(oldPath: string, newPath: string): Promise<void> ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/new.txt'; + let dstFile = pathDir + "/new.txt"; fs.rename(srcFile, dstFile).then(() => { console.info("rename succeed"); }).catch((err) => { @@ -1263,7 +1263,7 @@ rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): v ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/new.txt'; + let dstFile = pathDir + "/new.txt"; fs.rename(srcFile, dstFile, (err) => { if (err) { console.info("rename failed with error message: " + err.message + ", error code: " + err.code); @@ -1292,7 +1292,7 @@ renameSync(oldPath: string, newPath: string): void ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/new.txt'; + let dstFile = pathDir + "/new.txt"; fs.renameSync(srcFile, dstFile); ``` @@ -1498,7 +1498,7 @@ symlink(target: string, srcPath: string): Promise<void> ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/test'; + let dstFile = pathDir + "/test"; fs.symlink(srcFile, dstFile).then(() => { console.info("symlink succeed"); }).catch((err) => { @@ -1526,7 +1526,7 @@ symlink(target: string, srcPath: string, callback: AsyncCallback<void>): v ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/test'; + let dstFile = pathDir + "/test"; fs.symlink(srcFile, dstFile, (err) => { if (err) { console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); @@ -1555,7 +1555,7 @@ symlinkSync(target: string, srcPath: string): void ```js let srcFile = pathDir + "/test.txt"; - let dstFile = pathDir + '/test'; + let dstFile = pathDir + "/test"; fs.symlinkSync(srcFile, dstFile); ``` @@ -1606,7 +1606,7 @@ listFile(path: string, options?: { }; fs.listFile(pathDir, options).then((filenames) => { console.info("listFile succeed"); - for (let i = 0; i < filenames.size; i++) { + for (let i = 0; i < filenames.length; i++) { console.info("fileName: %s", filenames[i]); } }).catch((err) => { @@ -1657,7 +1657,7 @@ listFile(path: string, options?: { console.info("list file failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("listFile succeed"); - for (let i = 0; i < filenames.size; i++) { + for (let i = 0; i < filenames.length; i++) { console.info("filename: %s", filenames[i]); } } @@ -1710,13 +1710,13 @@ listFileSync(path: string, options?: { }; let filenames = fs.listFileSync(pathDir, options); console.info("listFile succeed"); - for (let i = 0; i < filenames.size; i++) { + for (let i = 0; i < filenames.length; i++) { console.info("filename: %s", filenames[i]); } ``` ## fs.moveFile -moveFile(src: string, dest: string, mode?: number): Promise; +moveFile(src: string, dest: string, mode?: number): Promise\; 移动文件,使用Promise异步回调。 @@ -1733,6 +1733,8 @@ moveFile(src: string, dest: string, mode?: number): Promise; **示例:** ```js + let srcPath = pathDir + "/source.txt"; + let destPath = pathDir + "/dest.txt"; fs.moveFile(srcPath, destPath, 0).then(() => { console.info("move file succeed"); }).catch((err) => { @@ -1742,7 +1744,7 @@ moveFile(src: string, dest: string, mode?: number): Promise; ## fs.moveFile -moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback): void; +moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\): void; 移动文件,使用Callback异步回调。 @@ -1760,6 +1762,8 @@ moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback **示例:** ```js + let srcPath = pathDir + "/source.txt"; + let destPath = pathDir + "/dest.txt"; fs.moveFile(srcPath, destPath, 0, (err) => { if (err) { console.info("move file failed with error message: " + err.message + ", error code: " + err.code); @@ -1788,6 +1792,8 @@ moveFile(src: string, dest: string, mode?: number): void; **示例:** ```js + let srcPath = pathDir + "/source.txt"; + let destPath = pathDir + "/dest.txt"; fs.moveFileSync(srcPath, destPath, 0); console.info("move file succeed"); ``` @@ -2578,7 +2584,7 @@ read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Prom let buf = new ArrayBuffer(4096); ss.read(buf, {offset: 5, length: 5}).then((readLen) => { console.info("read data succeed"); - console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); }).catch((err) => { console.info("read data failed with error message: " + err.message + ", error code: " + err.code); }); @@ -2612,7 +2618,7 @@ read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length console.info("read stream failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("read data succeed"); - console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); } }); ``` @@ -2660,7 +2666,7 @@ readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): ### lock -lock(exclusive?: boolean): Promise; +lock(exclusive?: boolean): Promise\; 文件阻塞式施加共享锁或独占锁,使用Promise异步回调。 @@ -2691,7 +2697,7 @@ lock(exclusive?: boolean): Promise; ### lock -lock(exclusive?: boolean, callback: AsyncCallback): void; +lock(exclusive?: boolean, callback: AsyncCallback\): void; 文件阻塞式施加共享锁或独占锁,使Callback异步回调。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md index a14b82314a97c1e7d99e69ecf1291bb32b718ece..1be063fa35b56ece8c98883bcbe49c63965b9b11 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md @@ -40,7 +40,7 @@ select(option?: PhotoSelectOptions) : Promise<PhotoSelectResult> | 类型 | 说明 | | ----------------------------- | :---- | -| [PhotoSelectResult](#photoselectresult) | 返回photoPicker选择后的结果集 | +| Promise<[PhotoSelectResult](#photoselectresult)> | Promise对象。返回photoPicker选择后的结果集 | **示例:** @@ -150,7 +150,7 @@ save(option?: PhotoSaveOptions) : Promise<Array<string>> | 类型 | 说明 | | ----------------------------- | :---- | -| <Array<string>> | 返回photoPicker保存图片或视频文件后的结果集 | +| Promise<Array<string>> | Promise对象。返回photoPicker保存图片或视频文件后的结果集 | **示例:** @@ -270,7 +270,7 @@ select(option?: DocumentSelectOptions) : Promise<Array<string>> | 类型 | 说明 | | ----------------------------- | :---- | -| <Array<string>> | 返回documentPicker选择后的结果集 | +| Promise<Array<string>> | Promise对象。返回documentPicker选择后的结果集 | **示例:** @@ -377,7 +377,7 @@ save(option?: DocumentSaveOptions) : Promise<Array<string>> | 类型 | 说明 | | ----------------------------- | :---- | -| <Array<string>> | 返回documentPicker保存后的结果集 | +| Promise<Array<string>> | Promise对象。返回documentPicker保存后的结果集 | **示例:** @@ -393,7 +393,7 @@ async function example() { console.error('DocumentViewPicker.save failed with err: ' + err); }); } catch (err) { - console.errort('DocumentViewPicker failed with err: ' + err); + console.error('DocumentViewPicker failed with err: ' + err); } } ``` @@ -429,7 +429,7 @@ async function example() { console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); } catch (err) { - console.errort('DocumentViewPicker failed with err: ' + err); + console.error('DocumentViewPicker failed with err: ' + err); } } ``` @@ -462,7 +462,7 @@ async function example() { console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); } catch (err) { - console.errort('DocumentViewPicker failed with err: ' + err); + console.error('DocumentViewPicker failed with err: ' + err); } } ``` @@ -497,7 +497,7 @@ select(option?: AudioSelectOptions) : Promise<Array<string>> | 类型 | 说明 | | ----------------------------- | :---- | -| <Array<string>> | 返回audioPicker选择音频后的结果集 | +| Promise<Array<string>> | Promise对象。返回audioPicker选择音频后的结果集 | **示例:** @@ -603,7 +603,7 @@ save(option?: AudioSaveOptions) : Promise<Array<string>> | 类型 | 说明 | | ----------------------------- | ---- | -| <Array<string>> | 返回audioPicker保存音频文件后的结果集 | +| Promise<Array<string>> | Promise对象。返回audioPicker保存音频文件后的结果集 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md b/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md index 3fbf979eaeb97928b5d92528c46067b18fbf3d52..d7110ee4df486c1824d88d152ec98b8325e165e8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -66,7 +66,8 @@ setSecurityLabel(path:string, type:DataLevel):Promise<void> **示例:** ```js - securityLabel.setSecurityLabel(path, "s0").then(() => { + let filePath = pathDir + '/test.txt'; + securityLabel.setSecurityLabel(filePath, "s0").then(() => { console.info("setSecurityLabel successfully"); }).catch((err) => { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); @@ -92,7 +93,8 @@ setSecurityLabel(path:string, type:DataLevel, callback: AsyncCallback<void> **示例:** ```js - securityLabel.setSecurityLabel(path, "s0", (err) => { + let filePath = pathDir + '/test.txt'; + securityLabel.setSecurityLabel(filePath, "s0", (err) => { if (err) { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -119,7 +121,8 @@ setSecurityLabelSync(path:string, type:DataLevel):void **示例:** ```js -securityLabel.setSecurityLabelSync(path, "s0"); +let filePath = pathDir + '/test.txt'; +securityLabel.setSecurityLabelSync(filePath, "s0"); ``` ## securityLabel.getSecurityLabel @@ -145,7 +148,8 @@ getSecurityLabel(path:string):Promise<string> **示例:** ```js - securityLabel.getSecurityLabel(path).then((type) => { + let filePath = pathDir + '/test.txt'; + securityLabel.getSecurityLabel(filePath).then((type) => { console.log("getSecurityLabel successfully, Label: " + type); }).catch((err) => { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); @@ -170,7 +174,8 @@ getSecurityLabel(path:string, callback:AsyncCallback<string>): void **示例:** ```js - securityLabel.getSecurityLabel(path, (err, type) => { + let filePath = pathDir + '/test.txt'; + securityLabel.getSecurityLabel(filePath, (err, type) => { if (err) { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -201,6 +206,7 @@ getSecurityLabelSync(path:string):string **示例:** ```js -let type = securityLabel.getSecurityLabelSync(path); +let filePath = pathDir + '/test.txt'; +let type = securityLabel.getSecurityLabelSync(filePath); console.log("getSecurityLabel successfully, Label: " + type); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md b/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md index 076072d2c1ba984bb5682fc4b55af8f3d91aa978..424cca1a83e12606d13f05772fe4bb3e1d2314d1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md @@ -22,9 +22,7 @@ getTotalSizeOfVolume(volumeUuid: string): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -59,9 +57,7 @@ getTotalSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -90,9 +86,7 @@ getFreeSizeOfVolume(volumeUuid: string): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -128,9 +122,7 @@ getFreeSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -159,9 +151,7 @@ getBundleStats(packageName: string): Promise<BundleStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -196,9 +186,7 @@ getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>) **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -263,11 +251,7 @@ getCurrentBundleStats(callback: AsyncCallback<BundleStats>): void ## BundleStats9+ -### 属性 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.StorageService.SpatialStatistics - - +**系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | --- | ---- | -------------- | @@ -286,9 +270,7 @@ getTotalSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -313,9 +295,7 @@ getTotalSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -332,7 +312,6 @@ getTotalSize(callback: AsyncCallback<number>): void }); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(): Promise<number> @@ -343,9 +322,7 @@ getFreeSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -360,7 +337,6 @@ getFreeSize(): Promise<number> console.info("getFreeSize successfully:"+ JSON.stringify(number)); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(callback: AsyncCallback<number>): void @@ -371,9 +347,7 @@ getFreeSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -400,9 +374,7 @@ getSystemSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -430,9 +402,7 @@ getSystemSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -459,9 +429,7 @@ getUserStorageStats(): Promise<StorageStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -489,9 +457,7 @@ getUserStorageStats(callback: AsyncCallback<StorageStats>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -515,9 +481,7 @@ getUserStorageStats(userId: number): Promise<StorageStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -552,9 +516,7 @@ getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>) **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -573,15 +535,11 @@ getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>) }); ``` - ## StorageStats9+ -### 属性 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.StorageService.SpatialStatistics - +**系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ----- | -------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md index 2f66868a47a28345d007b1320abbd349800f41d8..dcaf26d5b4cc123caf8eb62d8accf752fc2d8b3b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -6,6 +6,7 @@ fileAccess模块是基于extension机制实现的一个对公共文件访问和 > >- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >- 本模块接口为系统接口,三方应用不支持调用,当前只支持filepicker、文件管理器调用。 +>- 本模块支持对错误码进行处理,错误码及其适配方式[参考文档](../errorcodes/errorcode-filemanagement.md#错误码适配指导)。 ## 导入模块 @@ -1017,6 +1018,241 @@ access(sourceFileUri: string, callback: AsyncCallback<boolean>) : void; }; ``` +## FileAccessHelper.getFileInfoFromUri10+ + +getFileInfoFromUri(uri: string) : Promise; + +以异步方法获取uri对应的[FileInfo](#fileinfo)对象。使用promise异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | --- | --- | --- | -- | + | uri | string | 是 | 文件(夹)的Uri | + +**返回值:** + +| 类型 | 说明 | +| --- | -- | +| [FileInfo](#fileinfo) | FileInfo对象 | + +**示例:** + + ```js + // 以媒体库uri为例 + // 示例代码sourceUri表示Download目录,该uri是对应的fileInfo中uri + // 开发者应根据自己实际获取的uri进行开发 + let sourceUri = "datashare:///media/file/6"; + try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri); + } catch (error) { + console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getFileInfoFromUri10+ + +getFileInfoFromUri(uri: string, callback: AsyncCallback) : void; + +以异步方法获取uri对应的[FileInfo](#fileinfo)对象。使用callback异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | --- | --- | --- | -- | + | uri | string | 是 | 文件(夹)的Uri | + | callback | AsyncCallback<string> | 是 | uri对应的FileInfo对象 | + +**示例:** + + ```js + // 以媒体库uri为例 + // 示例代码sourceUri表示Download目录,该uri是对应的fileInfo中uri + // 开发者应根据自己实际获取的uri进行开发 + let sourceUri = "datashare:///media/file/6"; + try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileAccessHelper.getFileInfoFromUri(sourceUri, function (err, fileInfo) { + if (err) { + console.error("Failed to getFileInfoFromUri in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("getFileInfoFromUri success, fileInfo: " + JSON.stringify(fileInfo)); + }); + } catch (error) { + console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + + +## FileAccessHelper.getFileInfoFromRelativePath10+ + +getFileInfoFromRelativePath(relativePath: string) : Promise; + +以异步方法获取relativePath对应的[FileInfo](#fileinfo)对象。使用promise异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | --- | --- | --- | -- | + | relativePath | string | 是 | 文件(夹)的相对路径 | + +**返回值:** + +| 类型 | 说明 | +| --- | -- | +| [FileInfo](#fileinfo) | FileInfo对象 | + +**示例:** + + ```js + // 以媒体库relativePath为例 + // 示例代码relativePath表示Download目录,该relativePath是对应的fileInfo中relativePath + // 开发者应根据自己实际获取的relativePath进行开发 + let relativePath = "Download/"; + try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(relativePath); + } catch (error) { + console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getFileInfoFromRelativePath10+ + +getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback) : void; + +以异步方法获取relativePath对应的[FileInfo](#fileinfo)对象。使用callback异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | --- | --- | --- | -- | + | relativePath | string | 是 | 文件(夹)的相对路径 | + | callback | AsyncCallback<string> | 是 | relativePath对应的FileInfo对象 | + +**示例:** + + ```js + // 以媒体库relativePath为例 + // 示例代码relativePath表示Download目录,该relativePath是对应的fileInfo中relativePath + // 开发者应根据自己实际获取的relativePath进行开发 + let relativePath = "Download/"; + try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileAccessHelper.getFileInfoFromRelativePath(relativePath, function (err, fileInfo) { + if (err) { + console.error("Failed to getFileInfoFromRelativePath in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("getFileInfoFromRelativePath success, fileInfo: " + JSON.stringify(fileInfo)); + }); + } catch (error) { + console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.getThumbnail10+ + +getThumbnail(uri: string, size: image.Size) : Promise<image.PixelMap> + +通过指定uri和尺寸获取媒体文件的Pixelmap对象,使用Promise异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | ----------- | +| uri | string | 是 | 媒体文件uri | +| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸 | + +**返回值:** + +| 类型 | 说明 | +| :---------------------------- | :----------------- | +| Promise<image.PixelMap> | 返回的Pixelmap对象 | + +**示例:** + +```js +// 以媒体库uri为例 +// 示例代码targetUri表示Download目录下某个媒体文件(图片、音频、视频),该uri是对应的fileInfo中uri +// 开发者应根据自己实际获取的uri进行开发 +let targetUri = "datashare:///media/image/100"; +let size = { width: 128, height: 128 }; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + let pixelMap = await fileAccessHelper.getThumbnail(targetUri, size); + let imageInfo = await pixelMap.getImageInfo(); + console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); + console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); +} catch (error) { + console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); +}; +``` + +## FileAccessHelper.getThumbnail10+ + + getThumbnail(uri: string, size: image.Size, callback: AsyncCallback<image.PixelMap>) : void + +通过指定uri和尺寸获取媒体文件的Pixelmap对象,使用callback异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------ | +| uri | string | 是 | 媒体文件uri | +| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸 | +| callback | AsyncCallback<image.PixelMap> | 是 | 返回的Pixelmap对象 | + +**示例:** + +```js +// 以媒体库uri为例 +// 示例代码targetUri表示Download目录下某个媒体文件(图片、音频、视频),该uri是对应的fileInfo中uri +// 开发者应根据自己实际获取的uri进行开发 +let targetUri = "datashare:///media/image/100"; +let size = { width: 128, height: 128 }; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileAccessHelper.getThumbnail(targetUri, size, async(err, pixelMap) => { + if (err) { + console.error("Failed to getThumbnail in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + let imageInfo = await pixelMap.getImageInfo(); + console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); + console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); + }); +} catch (error) { + console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); +}; +``` + ## RootIterator.next next( ) : { value: RootInfo, done: boolean } @@ -1063,6 +1299,7 @@ FileIterator表示文件夹的迭代器对象,可以通过next同步方法获 | ------ | ------ | -------- | ------ | -------- | | deviceType | number | 是 | 否 |设备类型 | | uri | string | 是 | 否 | 设备根目录Uri | +| relativePath10+ | string | 是 | 否 | 根目录的相对路径 | | displayName | string | 是 | 否 | 设备名称 | | deviceFlags | number | 是 | 否 | 设备支持的能力 | @@ -1079,6 +1316,7 @@ FileIterator表示文件夹的迭代器对象,可以通过next同步方法获 | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | -------- | ------ | -------- | | uri | string | 是 | 否 | 文件(夹)的uri | +| relativePath10+ | string | 是 | 否 | 文件(夹)的相对路径 | | fileName | string | 是 | 否 | 文件(夹)的名称 | | mode | number | 是 | 否 | 文件(夹)的权限信息 | | size | number | 是 | 否 | 文件(夹)的大小 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileio.md b/zh-cn/application-dev/reference/apis/js-apis-fileio.md index 204537e9f0ff89cf89040682b07c8448cee57370..ab38374286a45e92cb12cb85bd450e5517d7ab30 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -30,7 +30,7 @@ export default class EntryAbility extends UIAbility { } ``` - Stage模型context的具体获取方法参见[Stage模型](js-apis-ability-context.md#abilitycontext)。 + Stage模型context的具体获取方法参见[Stage模型](js-apis-inner-application-uiAbilityContext.md)。 **FA模型** diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index 9de4f4b835bdf90523da4838d0ddaade3112884d..4fed31bc7e47b856011d64ba9679245080154ab2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -662,7 +662,7 @@ on(type: 'nmeaMessage', callback: Callback<string>): void; 订阅GNSS NMEA信息上报事件。 -**需要权限**:ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION +**需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION **系统能力**:SystemCapability.Location.Location.Gnss @@ -705,7 +705,7 @@ off(type: 'nmeaMessage', callback?: Callback<string>): void; 取消订阅GNSS NMEA信息上报事件。 -**需要权限**:ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION +**需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION **系统能力**:SystemCapability.Location.Location.Gnss @@ -882,7 +882,6 @@ on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | |3301000 | Location service is unavailable. | -|3301100 | The location switch is off. | |3301500 | Failed to query the area information. | @@ -924,7 +923,6 @@ off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | |3301000 | Location service is unavailable. | -|3301100 | The location switch is off. | |3301500 | Failed to query the area information. | **示例** 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 394a61c58f2034dd2e818c1a8561a6b12ec22496..5887ffaecdfd82e17bec2a2d38cf614db67fe11f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @@ -31,9 +31,10 @@ import hiAppEvent from '@ohos.hiAppEvent'; 事件参数为object类型,key为事件的参数名称,value为事件的参数值,其规格定义如下: - 参数名为string类型,字符串非空且长度在16个字符以内,有效的字符是0-9、a-z、下划线,只能以小写字母开头,不能以下划线结尾; -- 参数值支持string、number、boolean、Array类型; -- 参数值为string类型时,其长度需在8*1024个字符以内,超出会做截断处理; -- 参数值为Array类型时,Array中的元素类型只能全为string、number、boolean中的一种,且元素个数需在100以内,超出会做丢弃处理; +- 参数值支持string、number、boolean、数组类型; +- 参数值为string类型时,其长度需在8*1024个字符以内,超出会做丢弃处理; +- 参数值为number类型时,其取值需在Number.MIN_SAFE_INTEGER~Number.MAX_SAFE_INTEGER范围内,超出可能会产生不确定值; +- 参数值为数组类型时,数组中的元素类型只能全为string、number、boolean中的一种,且元素个数需在100以内,超出会做丢弃处理; - 参数个数需在32以内,超出的参数会做丢弃处理。 **事件回调** diff --git a/zh-cn/application-dev/reference/apis/js-apis-hichecker.md b/zh-cn/application-dev/reference/apis/js-apis-hichecker.md index b66101c41937973184db2f07fdbb06184173d37e..74cd7a0da311b6683b10fdb273047b376374cc71 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hichecker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hichecker.md @@ -122,7 +122,9 @@ try { addRule(rule: bigint): void -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.addCheckRule](#hicheckeraddcheckrule9)替代。 +> **说明:** +> +> 从 API Version 9 开始废弃,建议使用[hichecker.addCheckRule](#hicheckeraddcheckrule9)替代。 添加一条或多条规则到系统,系统根据添加的规则进行检测或反馈。 @@ -149,7 +151,9 @@ hichecker.addRule( removeRule(rule: bigint): void -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.removeCheckRule](#hicheckerremovecheckrule9)替代。 +> **说明:** +> +> 从 API Version 9 开始废弃,建议使用[hichecker.removeCheckRule](#hicheckerremovecheckrule9)替代。 删除一条或多条规则,删除的规则后续将不再生效。 @@ -200,7 +204,9 @@ hichecker.getRule(); // return 1n; contains(rule: bigint): boolean -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.containsCheckRule](#hicheckercontainscheckrule9)替代。 +> **说明:** +> +> 从 API Version 9 开始废弃,建议使用[hichecker.containsCheckRule](#hicheckercontainscheckrule9)替代。 当前已添加的规则集中是否包含了某一个特定的规则,如果传入的规则级别为线程级别,则仅在当前线程中进行查询。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md index 66306729dc0da5f124d69eb0f9865c17b4259048..fcdd7111bdb85cac4e21a5c6ca38dcde45148840 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md @@ -19,8 +19,6 @@ getNativeHeapSize(): bigint 获取本应用堆内存的总大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -29,21 +27,17 @@ getNativeHeapSize(): bigint | ------ | --------------------------- | | bigint | 返回本应用堆内存总大小,单位为kB。 | - **示例:** ```js let nativeHeapSize = hidebug.getNativeHeapSize(); ``` - ## hidebug.getNativeHeapAllocatedSize getNativeHeapAllocatedSize(): bigint 获取本应用堆内存的已分配内存大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -58,15 +52,12 @@ getNativeHeapAllocatedSize(): bigint let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); ``` - ## hidebug.getNativeHeapFreeSize getNativeHeapFreeSize(): bigint 获取本应用堆内存的空闲内存大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -80,7 +71,6 @@ getNativeHeapFreeSize(): bigint let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); ``` - ## hidebug.getPss getPss(): bigint @@ -100,7 +90,6 @@ getPss(): bigint let pss = hidebug.getPss(); ``` - ## hidebug.getSharedDirty getSharedDirty(): bigint @@ -135,7 +124,6 @@ getPrivateDirty(): bigint | ------ | -------------------------- | | bigint | 返回进程的私有脏内存大小,单位为kB。 | - **示例:** ```js let privateDirty = hidebug.getPrivateDirty(); @@ -163,76 +151,6 @@ getCpuUsage(): number let cpuUsage = hidebug.getCpuUsage(); ``` -## hidebug.startProfiling(deprecated) - -startProfiling(filename : string) : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9)替代。 - -启动虚拟机Profiling方法跟踪,`startProfiling()`方法的调用需要与`stopProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | - -**示例:** - -```js -hidebug.startProfiling("cpuprofiler-20220216"); -// code block -// ... -// code block -hidebug.stopProfiling(); -``` - - - -## hidebug.stopProfiling(deprecated) - -stopProfiling() : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9)替代。 - -停止虚拟机Profiling方法跟踪,`stopProfiling()`方法的调用需要与`startProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**示例:** - -```js -hidebug.startProfiling("cpuprofiler-20220216"); -// code block -// ... -// code block -hidebug.stopProfiling(); -``` - -## hidebug.dumpHeapData(deprecated) - -dumpHeapData(filename : string) : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9)替代。 - -虚拟机堆导出。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | 是 | 用户自定义的虚拟机堆文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.heapsnapshot`文件。 | - -**示例:** - -```js -hidebug.dumpHeapData("heap-20220216"); -``` - ## hidebug.getServiceDump9+ getServiceDump(serviceid : number, fd : number, args : Array\) : void @@ -359,4 +277,72 @@ try { console.info(error.code) console.info(error.message) } -``` \ No newline at end of file +``` + +## hidebug.startProfiling(deprecated) + +startProfiling(filename : string) : void + +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9)替代。 + +启动虚拟机Profiling方法跟踪,`startProfiling()`方法的调用需要与`stopProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | + +**示例:** + +```js +hidebug.startProfiling("cpuprofiler-20220216"); +// code block +// ... +// code block +hidebug.stopProfiling(); +``` + +## hidebug.stopProfiling(deprecated) + +stopProfiling() : void + +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9)替代。 + +停止虚拟机Profiling方法跟踪,`stopProfiling()`方法的调用需要与`startProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**示例:** + +```js +hidebug.startProfiling("cpuprofiler-20220216"); +// code block +// ... +// code block +hidebug.stopProfiling(); +``` + +## hidebug.dumpHeapData(deprecated) + +dumpHeapData(filename : string) : void + +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9)替代。 + +虚拟机堆导出。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的虚拟机堆文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.heapsnapshot`文件。 | + +**示例:** + +```js +hidebug.dumpHeapData("heap-20220216"); +``` 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 index f8ce582776b930ad6a65a0cb54a082e00c2120f6..2c41ccc0392e70edb1e2d0c40870bf1cbbdeee6b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -120,12 +120,12 @@ hiAppEvent.write({ **系统能力:** SystemCapability.HiviewDFX.HiAppEvent -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------- | -| domain | string | 是 | 事件领域。 | -| name | string | 是 | 事件名称。 | -| eventType | [EventType](#eventtype) | 是 | 事件类型。 | -| params | object | 是 | 事件参数。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------------------------------------------------------ | +| domain | string | 是 | 事件领域。事件领域名称支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过32个字符。 | +| name | string | 是 | 事件名称。事件名称支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过48个字符。 | +| eventType | [EventType](#eventtype) | 是 | 事件类型。 | +| params | object | 是 | 事件参数对象,每个事件参数包括参数名和参数值,其规格定义如下:
- 参数名为string类型,只支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过16个字符。
- 参数值支持string、number、boolean、数组类型,string类型参数长度需在8*1024个字符以内,超出会做丢弃处理;number类型参数取值需在Number.MIN_SAFE_INTEGER~Number.MAX_SAFE_INTEGER范围内,超出可能会产生不确定值;数组类型参数中的元素类型只能全为string、number、boolean中的一种,且元素个数需在100以内,超出会做丢弃处理。
- 参数个数需在32个以内,超出的参数会做丢弃处理。 | ## hiAppEvent.configure diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index 1cdf224165953ca89bc5d02298ff045a4f45b23c..afdc43e1e0896d996ac9512e096c6feef6666800 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -67,7 +67,7 @@ httpRequest.request( ## http.createHttp -createHttp\(\): HttpRequest +createHttp(): HttpRequest 创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。 @@ -77,7 +77,7 @@ createHttp\(\): HttpRequest | 类型 | 说明 | | :---------- | :----------------------------------------------------------- | -| HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 | +| HttpRequest | 返回一个HttpRequest对象,里面包括request、request2、destroy、on和off方法。 | **示例:** @@ -88,14 +88,17 @@ let httpRequest = http.createHttp(); ## HttpRequest -HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。 +HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp()](#httpcreatehttp)创建一个任务。 ### request -request\(url: string, callback: AsyncCallback\\):void +request(url: string, callback: AsyncCallback\):void 根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。 +>**说明:** +>此接口仅支持数据大小为5M以内的数据传输。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -140,10 +143,13 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { ### request -request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\\):void +request(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void 根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。 +>**说明:** +>此接口仅支持数据大小为5M以内的数据传输。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -223,10 +229,13 @@ httpRequest.request("EXAMPLE_URL", ### request -request\(url: string, options? : HttpRequestOptions\): Promise\ +request(url: string, options? : HttpRequestOptions): Promise\ 根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 +>**说明:** +>此接口仅支持数据大小为5M以内的数据传输。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -309,7 +318,7 @@ promise.then((data) => { ### destroy -destroy\(\): void +destroy(): void 中断请求任务。 @@ -323,7 +332,7 @@ httpRequest.destroy(); ### request210+ -request2(url: string, callback: AsyncCallback): void +request2(url: string, callback: AsyncCallback\): void 根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 @@ -359,7 +368,7 @@ request2(url: string, callback: AsyncCallback): void ```js httpRequest.request2("EXAMPLE_URL", (err) => { if (!err) { - console.info(request2 OK!); + console.info("request2 OK!"); } else { console.info("request2 ERROR : err = " + JSON.stringify(err)); } @@ -368,7 +377,7 @@ httpRequest.request2("EXAMPLE_URL", (err) => { ### request210+ -request2(url: string, options: HttpRequestOptions, callback: AsyncCallback): void +request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void 根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 @@ -437,7 +446,7 @@ httpRequest.request2("EXAMPLE_URL", connectTimeout: 60000 }, (err) => { if (!err) { - console.info(request2 OK!); + console.info("request2 OK!"); } else { console.info("request2 ERROR : err = " + JSON.stringify(err)); } @@ -445,7 +454,7 @@ httpRequest.request2("EXAMPLE_URL", ``` ### request210+ -request2\(url: string, options? : HttpRequestOptions\): Promise\ +request2(url: string, options? : HttpRequestOptions): Promise\ 根据URL地址,发起HTTP网络请求并返回流式响应,使用Promise方式作为异步方法。 @@ -518,20 +527,20 @@ let promise = httpRequest.request("EXAMPLE_URL", { } }); promise.then(() => { - console.info(request2 OK!); + console.info("request2 OK!"); }).catch((err) => { console.info("request2 ERROR : err = " + JSON.stringify(err)); }); ``` -### on\('headerReceive'\) +### on('headerReceive') -on\(type: 'headerReceive', callback: AsyncCallback\): void +on(type: 'headerReceive', callback: AsyncCallback\): void 订阅HTTP Response Header 事件。 ->![](public_sys-resources/icon-note.gif) **说明:** ->此接口已废弃,建议使用[on\('headersReceive'\)8+](#onheadersreceive8)替代。 +>**说明:** +>此接口已废弃,建议使用[on('headersReceive')8+](#onheadersreceive8)替代。 **系统能力**:SystemCapability.Communication.NetStack @@ -545,24 +554,20 @@ on\(type: 'headerReceive', callback: AsyncCallback\): void **示例:** ```js -httpRequest.on('headerReceive', (err, data) => { - if (!err) { - console.info('header: ' + JSON.stringify(data)); - } else { - console.info('error:' + JSON.stringify(err)); - } +httpRequest.on('headerReceive', (data) => { + console.info('error:' + JSON.stringify(data)); }); ``` -### off\('headerReceive'\) +### off('headerReceive') -off\(type: 'headerReceive', callback?: AsyncCallback\): void +off(type: 'headerReceive', callback?: AsyncCallback\): void 取消订阅HTTP Response Header 事件。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** > ->1. 此接口已废弃,建议使用[off\('headersReceive'\)8+](#offheadersreceive8)替代。 +>1. 此接口已废弃,建议使用[off('headersReceive')8+](#offheadersreceive8)替代。 > >2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -581,9 +586,9 @@ off\(type: 'headerReceive', callback?: AsyncCallback\): void httpRequest.off('headerReceive'); ``` -### on\('headersReceive'\)8+ +### on('headersReceive')8+ -on\(type: 'headersReceive', callback: Callback\): void +on(type: 'headersReceive', callback: Callback\): void 订阅HTTP Response Header 事件。 @@ -604,13 +609,13 @@ httpRequest.on('headersReceive', (header) => { }); ``` -### off\('headersReceive'\)8+ +### off('headersReceive')8+ -off\(type: 'headersReceive', callback?: Callback\): void +off(type: 'headersReceive', callback?: Callback\): void 取消订阅HTTP Response Header 事件。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -628,9 +633,9 @@ off\(type: 'headersReceive', callback?: Callback\): void httpRequest.off('headersReceive'); ``` -### once\('headersReceive'\)8+ +### once('headersReceive')8+ -once\(type: 'headersReceive', callback: Callback\): void +once(type: 'headersReceive', callback: Callback\): void 订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。 @@ -650,9 +655,9 @@ httpRequest.once('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); ``` -### on\('dataReceive'\)10+ +### on('dataReceive')10+ -on\(type: 'dataReceive', callback: Callback\\): void +on(type: 'dataReceive', callback: Callback\): void 订阅HTTP流式响应数据接收事件。 @@ -673,13 +678,13 @@ httpRequest.on('dataReceive', (data) => { }); ``` -### off\('dataReceive'\)10+ +### off('dataReceive')10+ -off\(type: 'dataReceive', callback?: Callback\\): void +off(type: 'dataReceive', callback?: Callback\): void 取消订阅HTTP流式响应数据接收事件。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -697,9 +702,9 @@ off\(type: 'dataReceive', callback?: Callback\\): void httpRequest.off('dataReceive'); ``` -### on\('dataEnd'\)10+ +### on('dataEnd')10+ -on\(type: 'dataEnd', callback: Callback\\): void +on(type: 'dataEnd', callback: Callback\): void 订阅HTTP流式响应数据接收完毕事件。 @@ -720,13 +725,13 @@ httpRequest.on('dataReceive', () => { }); ``` -### off\('dataEnd'\)10+ +### off('dataEnd')10+ off(type: 'dataEnd', callback?: Callback\): void 取消订阅HTTP流式响应数据接收完毕事件。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -744,9 +749,9 @@ off(type: 'dataEnd', callback?: Callback\): void httpRequest.off('dataEnd'); ``` -### on\('dataProgress'\)10+ +### on('dataProgress')10+ - on\(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>\): void + on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void 订阅HTTP流式响应数据接收进度事件。 @@ -757,25 +762,23 @@ httpRequest.off('dataEnd'); | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | --------------------------------- | | type | string | 是 | 订阅的事件类型,'dataProgress'。 | -| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | 是 | 回调函数。 | +| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | 是 | 回调函数。
receiveSize:已接收的数据字节数,totalSize待接收的字节总数 | **示例:** ```js httpRequest.on('dataProgress', (data) => { - if (!err) { - console.info('dataProgress:' + JSON.stringify(data)); - } + console.info('dataProgress:' + JSON.stringify(data)); }); ``` -### off\('dataProgress'\)10+ +### off('dataProgress')10+ off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void 取消订阅HTTP流式响应数据接收进度事件。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -796,7 +799,7 @@ httpRequest.off('dataProgress'); 发起请求可选参数的类型和取值范围。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | @@ -815,7 +818,7 @@ httpRequest.off('dataProgress'); HTTP 请求方法。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 值 | 说明 | | :------ | ------- | :------------------ | @@ -832,7 +835,7 @@ HTTP 请求方法。 发起请求返回的响应码。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 值 | 说明 | | ----------------- | ---- | ------------------------------------------------------------ | @@ -876,7 +879,7 @@ HTTP 请求方法。 request方法回调函数的返回值类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | @@ -915,11 +918,11 @@ let httpResponseCache = http.createHttpResponseCache(); ## HttpResponseCache9+ -存储HTTP访问请求响应的对象。 +存储HTTP访问请求响应的对象。在调用HttpResponseCache的方法前,需要先通过[createHttpResponseCache()](#httpcreatehttpresponsecache9)创建一个任务。 ### flush9+ -flush(callback: AsyncCallback\): void +flush(callback: AsyncCallback\): void 将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。 @@ -929,7 +932,7 @@ flush(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数返回写入结果。 | +| callback | AsyncCallback\ | 是 | 回调函数返回写入结果。 | **示例:** @@ -945,7 +948,7 @@ httpResponseCache.flush(err => { ### flush9+ -flush(): Promise\ +flush(): Promise\ 将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。 @@ -955,7 +958,7 @@ flush(): Promise\ | 类型 | 说明 | | --------------------------------- | ------------------------------------- | -| Promise\> | 以Promise形式返回写入结果。 | +| Promise\ | 以Promise形式返回写入结果。 | **示例:** @@ -969,7 +972,7 @@ httpResponseCache.flush().then(() => { ### delete9+ -delete(callback: AsyncCallback\): void +delete(callback: AsyncCallback\): void 禁用缓存并删除其中的数据,使用callback方式作为异步方法。 @@ -979,7 +982,7 @@ delete(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数返回删除结果。| +| callback | AsyncCallback\ | 是 | 回调函数返回删除结果。| **示例:** @@ -994,7 +997,7 @@ httpResponseCache.delete(err => { ``` ### delete9+ -delete(): Promise\ +delete(): Promise\ 禁用缓存并删除其中的数据,使用Promise方式作为异步方法。 @@ -1004,7 +1007,7 @@ delete(): Promise\ | 类型 | 说明 | | --------------------------------- | ------------------------------------- | -| Promise\ | 以Promise形式返回删除结果。 | +| Promise\ | 以Promise形式返回删除结果。 | **示例:** @@ -1023,7 +1026,7 @@ http的数据类型。 **系统能力**:SystemCapability.Communication.NetStack | 名称 | 值 | 说明 | -| ------------------ | -- | ----------- | +| ------------------ | -- | ----------- | | STRING | 0 | 字符串类型。 | | OBJECT | 1 | 对象类型。 | | ARRAY_BUFFER | 2 | 二进制数组类型。| 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 e69ecb237c9c3097bed2036b013531fe27d3d6f6..d7c79dfb6b106fe077fa7ecd50646322b6483253 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-huks.md +++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md @@ -1818,9 +1818,9 @@ async function huksAbort() { | 名称 | 值 | 说明 | | ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | 表示用户认证类型为指纹。 | -| HUKS_USER_AUTH_TYPE_FACE | 2 | 表示用户认证类型为人脸 。 | -| HUKS_USER_AUTH_TYPE_PIN | 4 | 表示用户认证类型为PIN码。 | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 << 0 | 表示用户认证类型为指纹。 | +| HUKS_USER_AUTH_TYPE_FACE | 1 << 1 | 表示用户认证类型为人脸 。 | +| HUKS_USER_AUTH_TYPE_PIN | 1 << 2 | 表示用户认证类型为PIN码。 | ## HuksAuthAccessType9+ @@ -1830,8 +1830,8 @@ async function huksAbort() { | 名称 | 值 | 说明 | | --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | 表示安全访问控制类型为清除密码后密钥无效。 | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | 表示安全访问控制类型为新录入生物特征后密钥无效。 | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 << 0 | 表示安全访问控制类型为清除密码后密钥无效。 | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 1 << 1 | 表示安全访问控制类型为新录入生物特征后密钥无效。 | ## HuksChallengeType9+ @@ -1892,7 +1892,7 @@ async function huksAbort() { | 名称 | 值 | 说明 | | -------------------------------------------- | ---------------------------------------- | -------------------------------------- | | HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | 表示非法的Tag。 | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | 表示算法的Tag。 | +| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | 表示算法的Tag。 | | HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | 表示密钥用途的Tag。 | | HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | 表示密钥长度的Tag。 | | HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | 表示摘要算法的Tag。 | @@ -1922,7 +1922,7 @@ async function huksAbort() { | HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | 预留。 | | HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | 预留。 | | HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | 预留。 | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | 预留。 | +| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | 预留。 | | HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | 预留。 | | HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | 预留。 | | HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | 表示用户认证类型。从[HuksUserAuthType](#huksuserauthtype9)中选择,需要与安全访问控制类型同时设置。支持同时指定两种用户认证类型,如:安全访问控制类型指定为HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL时,密钥访问认证类型可以指定以下三种: HKS_USER_AUTH_TYPE_FACE 、HKS_USER_AUTH_TYPE_FINGERPRINT、HKS_USER_AUTH_TYPE_FACE \| HKS_USER_AUTH_TYPE_FINGERPRINT | @@ -2889,11 +2889,6 @@ huks Handle结构体。 | HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |表示存在新的根密钥材料。| | HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |表示更新根密钥材料失败。| | HUKS_ERROR_VERIFICATION_FAILED | -38 |表示验证证书链失败。| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |表示获取当前用户安全属性信息失败。| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |表示获取当前用户认证信息失败。| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |表示不支持当前用户认证类型的访问控制。| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |表示安全访问控制认证失败。| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |表示设备当前未录入凭据。| | HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |表示检查获取 ALG 失败。| | HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |表示检查获取密钥大小失败。| | HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |表示检查获取填充失败。| @@ -2920,7 +2915,5 @@ huks Handle结构体。 | HUKS_ERROR_INVALID_SALT | -123 |表示无效SALT。| | HUKS_ERROR_INVALID_ITERATION | -124 |表示无效的迭代。| | HUKS_ERROR_INVALID_OPERATION | -125 |表示无效操作。| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |表示导入加密密钥时,密钥格式错误。| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |表示导入加密密钥时,密钥用途错误。| | HUKS_ERROR_INTERNAL_ERROR | -999 |表示内部错误。| | HUKS_ERROR_UNKNOWN_ERROR | -1000 |表示未知错误。| \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-i18n.md b/zh-cn/application-dev/reference/apis/js-apis-i18n.md index 44256b9542e9a4ce38a6b11475e6dcba71bb4f71..c2e88eeed1b761482ec958b0add5357f69c07fbc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-i18n.md +++ b/zh-cn/application-dev/reference/apis/js-apis-i18n.md @@ -1059,7 +1059,7 @@ constructor(country: string, options?: PhoneNumberFormatOptions) | 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------- | | country | string | 是 | 表示电话号码所属国家或地区代码。 | -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | 否 | 电话号码格式化对象的相关选项。 | +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | 否 | 电话号码格式化对象的相关选项。 | **示例:** ```js @@ -1149,7 +1149,7 @@ getLocationName(number: string, locale: string): string ``` -## PhoneNumberFormatOptions8+ +## PhoneNumberFormatOptions9+ 表示电话号码格式化对象可设置的属性。 @@ -1194,7 +1194,7 @@ getInstance(locale?:string): IndexUtil **示例:** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); ``` @@ -1267,7 +1267,7 @@ getIndex(text: string): string **示例:** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); let index = indexUtil.getIndex("hi"); // index = "H" ``` @@ -1382,7 +1382,7 @@ first(): number **示例:** ```js - let iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let firstPos = iterator.first(); // firstPos = 0 ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md index b08aa4862fdb7c553b6b1fe5e1ffb648687d6e08..8c0eb7fb0049de9da17c35d9c82f0e66e6483fb1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -947,8 +947,18 @@ createImageSource(uri: string): ImageSource **示例:** ```js -let context = featureAbility.getContext(); -let path = context.getCacheDir() + "test.jpg"; +//Stage模型 +const context = getContext(this); +const path = context.getCacheDir() + "/test.jpg"; +const imageSourceApi = image.createImageSource(path); +``` + +```js +//FA模型 +import featureAbility from '@ohos.ability.featureAbility'; + +const context = featureAbility.getContext(); +const path = context.getCacheDir() + "/test.jpg"; const imageSourceApi = image.createImageSource(path); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 2d736dafd9e04e113f4310b0aad0d5939ac49c76..5afc8692841976d2ee9438812d521c17f0c4a928 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -27,11 +27,9 @@ function executeBatchOperation() { DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); if (DAHelper === null) { console.error('DAHelper is null'); - return; } } catch (err) { console.error('acquireDataAbilityHelper fail, error: ${JSON.stringify(err)}'); - return; } let valueBucket = { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 654266d918243b97d796ce135eb35e3669b37ece..2a99f0569c097c6f367159fde9d8ae161f29d6ea 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -11,8 +11,6 @@ AbilityDelegator提供添加用于监视指定ability的生命周期状态更改 通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。 ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; - -let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ## AbilityDelegator @@ -492,8 +490,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => { - console.info('doAbilityForeground callback'); + abilityDelegator.doAbilityForeground(ability, (err : any) => { + console.info("doAbilityForeground callback"); }); }); ``` @@ -528,8 +526,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityForeground(ability).then((data : any) => { - console.info('doAbilityForeground promise'); + abilityDelegator.doAbilityForeground(ability).then(() => { + console.info("doAbilityForeground promise"); }); }); ``` @@ -559,8 +557,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => { - console.info('doAbilityBackground callback'); + abilityDelegator.doAbilityBackground(ability, (err : any) => { + console.info("doAbilityBackground callback"); }); }); ``` @@ -595,8 +593,8 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info('getCurrentTopAbility callback'); ability = data; - abilityDelegator.doAbilityBackground(ability).then((data : any) => { - console.info('doAbilityBackground promise'); + abilityDelegator.doAbilityBackground(ability).then(() => { + console.info("doAbilityBackground promise"); }); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 91a31e1e435b861c6e867c9621d818d2cf024c22..1f45af02032486ff5cc5b4ad33ed54438a637a3f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -34,7 +34,7 @@ class EntryAbility extends AccessibilityExtensionAbility { | 名称 | 说明 | | -------- | ------- | | up | 表示向上查询。 | -| down | 表示向上查询。 | +| down | 表示向下查询。 | | left | 表示向左查询。 | | right | 表示向右查询。 | | forward | 表示向前查询。 | @@ -131,7 +131,7 @@ setTargetBundleName(targetNames: Array\, callback: AsyncCallback\) let targetNames = ['com.ohos.xyz']; try { axContext.setTargetBundleName(targetNames, (err, data) => { - if (err) { + if (err && err.code) { console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); return; } @@ -214,7 +214,7 @@ getFocusElement(callback: AsyncCallback\): void; let focusElement; try { axContext.getFocusElement((err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get focus element, because ${JSON.stringify(err)}'); return; } @@ -248,7 +248,7 @@ let focusElement; let isAccessibilityFocus = true; try { axContext.getFocusElement(isAccessibilityFocus, (err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get focus element, because ${JSON.stringify(err)}'); return; } @@ -331,7 +331,7 @@ getWindowRootElement(callback: AsyncCallback\): void; let rootElement; try { axContext.getWindowRootElement((err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); return; } @@ -373,7 +373,7 @@ let rootElement; let windowId = 10; try { axContext.getWindowRootElement(windowId, (err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); return; } @@ -457,7 +457,7 @@ getWindows(callback: AsyncCallback\>): void; let windows; try { axContext.getWindows((err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get windows, because ${JSON.stringify(err)}'); return; } @@ -499,7 +499,7 @@ let windows; let displayId = 10; try { axContext.getWindows(displayId, (err, data) => { - if (err) { + if (err && err.code) { console.error('failed to get windows, because ${JSON.stringify(err)}'); return; } @@ -594,7 +594,7 @@ try { gesturePath.points.push(gesturePoint); } axContext.injectGesture(gesturePath, (err, data) => { - if (err) { + if (err && err.code) { console.error('failed to inject gesture, because ${JSON.stringify(err)}'); return; } @@ -818,7 +818,7 @@ performAction(actionName: string, parameters?: object): Promise\; | 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | 是 | 表示属性的名称。 | +| actionName | string | 是 | 表示属性的名称,取值参考[Action](./js-apis-accessibility.md#action)。 | parameters | object | 否 | 表示执行操作时所需要的参数。 | **返回值:** @@ -861,7 +861,7 @@ performAction(actionName: string, callback: AsyncCallback\): void; | 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | 是 | 表示属性的名称。 | +| actionName | string | 是 | 表示属性的名称,取值参考[Action](./js-apis-accessibility.md#action)。 | callback | AsyncCallback<void> | 是 | 回调函数,表示执行指定操作的回调。| **错误码:** @@ -900,7 +900,7 @@ performAction(actionName: string, parameters: object, callback: AsyncCallback\ { + applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => { if (error && error.code !== 0) { console.error('unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}'); } else { @@ -152,7 +152,7 @@ export default class MyAbility extends Ability { onDestroy() { let applicationContext = this.context.getApplicationContext(); console.log('stage applicationContext: ${applicationContext}'); - applicationContext.off(type: 'abilityLifecycle', lifecycleId); + applicationContext.off('abilityLifecycle', lifecycleId); } } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md index ee31283918f377d19d78cd89fe5c4f91d269286c..4cd21a38f960a8018100082cd70ad502b6722477 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -31,9 +31,13 @@ let listener = { onMissionMovedToFront: function (mission) { console.log('onMissionMovedToFront mission: ${JSON.stringify(mission)}'); }, - onMissionIconUpdated: function (mission, icon) { - console.log('onMissionIconUpdated mission: ${JSON.stringify(mission)}'); + onMissionLabelUpdated: function (mission) { + console.log('onMissionLabelUpdated mission: ' + JSON.stringify(mission)); }, + onMissionIconUpdated: function (mission, icon) { + console.log('onMissionIconUpdated mission: ' + JSON.stringify(mission)); + console.log('onMissionIconUpdated icon: ' + JSON.stringify(icon)); + }, onMissionClosed: function (mission) { console.log('onMissionClosed mission: ${JSON.stringify(mission)}'); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md new file mode 100644 index 0000000000000000000000000000000000000000..e84f3b4abffbb032a8a79c489a780ad252158737 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md @@ -0,0 +1,11 @@ +# CommonEventData + +**系统能力:** `SystemCapability.Notification.CommonEvent` + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | 是 | 否 | 表示当前接收的公共事件名称。 | +| bundleName | string | 是 | 否 | 表示包名称。 | +| code | number | 是 | 否 | 表示公共事件的结果代码,用于传递int类型的数据。 | +| data | string | 是 | 否 | 表示公共事件的自定义结果数据,用于传递string类型的数据。 | +| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md new file mode 100644 index 0000000000000000000000000000000000000000..9d5fe786465e99ce4e85c49310943df600ccb8e6 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md @@ -0,0 +1,13 @@ +# CommonEventPublishData + +**系统能力:** `SystemCapability.Notification.CommonEvent` + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | 是 | 否 | 表示包名称。 | +| code | number | 是 | 否 | 表示公共事件的结果代码。 | +| data | string | 是 | 否 | 表示公共事件的自定义结果数据。 | +| subscriberPermissions | Array\ | 是 | 否 | 表示订阅者的权限。 | +| isOrdered | boolean | 是 | 否 | 表示是否是有序事件。 | +| isSticky | boolean | 是 | 否 | 表示是否是粘性事件。仅系统应用或系统服务允许发送粘性事件。 | +| parameters | {[key: string]: any} | 是 | 否 | 表示公共事件的附加信息。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..6938b5351b61ab96cf8d87cc78fc3333af21cfa6 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md @@ -0,0 +1,11 @@ +# CommonEventSubscribeInfo + +**系统能力:** `SystemCapability.Notification.CommonEvent` + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | 是 | 否 | 表示要发送的公共事件。 | +| publisherPermission | string | 是 | 否 | 表示发布者的权限。 | +| publisherDeviceId | string | 是 | 否 | 表示设备ID,该值必须是同一ohos网络上的现有设备ID。 | +| userId | number | 是 | 否 | 表示用户ID。此参数是可选的,默认值当前用户的ID。如果指定了此参数,则该值必须是系统中现有的用户ID。 | +| priority | number | 是 | 否 | 表示订阅者的优先级。值的范围是-100到1000。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md new file mode 100644 index 0000000000000000000000000000000000000000..411b63e250403b1f5ee916d273f5306c88cda65c --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -0,0 +1,750 @@ +# CommonEventSubscriber + +## getCode + +```ts +getCode(callback: AsyncCallback): void +``` + +以回调形式获取公共事件代码。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | 是 | 公共事件代码。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取有序公共事件代码回调 +function getCodeCB(err, code) { + if (err.code) { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getCode " + JSON.stringify(code)); + } +} +subscriber.getCode(getCodeCB); +``` + +## getCode + +```ts +getCode(): Promise +``` + +以Promise形式获取公共事件代码。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 公共事件代码。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.getCode().then((code) => { + console.info("getCode " + JSON.stringify(code)); +}).catch((err) => { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setCode + +```ts +setCode(code: number, callback: AsyncCallback): void +``` + +以回调形式设置公共事件的代码。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的代码。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的代码回调 +function setCodeCB(err) { + if (err.code) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCB); +``` + +## setCode + +```ts +setCode(code: number): Promise +``` + +以Promise形式设置公共事件的代码。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| code | number | 是 | 公共事件的代码。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getData + +```ts +getData(callback: AsyncCallback): void +``` + +以回调形式获取公共事件的数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 公共事件的数据。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取有序公共事件代码数据回调 +function getDataCB(err, data) { + if (err.code) { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getData " + JSON.stringify(data)); + } +} +subscriber.getData(getDataCB); +``` + +## getData + +```ts +getData(): Promise +``` + +以Promise形式获取公共事件的数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------ | +| Promise\ | 公共事件的数据。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.getData().then((data) => { + console.info("getData " + JSON.stringify(data)); +}).catch((err) => { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setData + +setData(data: string, callback: AsyncCallback\): void + +以回调形式设置公共事件的数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| data | string | 是 | 公共事件的数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果数据回调 +function setDataCB(err) { + if (err.code) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCB); +``` + +## setData + +```ts +setData(data: string): Promise +``` + +以Promise形式设置公共事件的果数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------- | +| data | string | 是 | 公共事件的数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## setCodeAndData + +```ts +setCodeAndData(code: number, data: string, callback:AsyncCallback): void +``` + +以回调形式设置公共事件代码和数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的代码。 | +| data | string | 是 | 公共事件的数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的代码和数据回调 +function setCodeDataCB(err) { + if (err.code) { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); +``` + +## setCodeAndData + +```ts +setCodeAndData(code: number, data: string): Promise +``` + +以Promise形式设置公共事件的代码和数据。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------- | +| code | number | 是 | 公共事件的代码。 | +| data | string | 是 | 公共事件的数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## isOrderedCommonEvent + +```ts +isOrderedCommonEvent(callback: AsyncCallback): void +``` + +以回调形式查询当前公共事件的是否为有序公共事件。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为有序事件的回调 +function isOrderedCB(err, isOrdered) { + if (err.code) { + console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCB); +``` + +## isOrderedCommonEvent + +```ts +isOrderedCommonEvent(): Promise +``` + +以Promise形式查询当前公共事件的是否为有序公共事件。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## isStickyCommonEvent + +```ts +isStickyCommonEvent(callback: AsyncCallback): void +``` + +以回调形式检查当前公共事件是否为一个粘性事件。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为粘性事件的回调 +function isStickyCB(err, isSticky) { + if (err.code) { + console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCB); +``` + +## isStickyCommonEvent + +```ts +isStickyCommonEvent(): Promise +``` + +以Promise形式检查当前公共事件是否为一个粘性事件。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## abortCommonEvent + +```ts +abortCommonEvent(callback: AsyncCallback): void +``` + +以回调形式取消当前的有序公共事件,取消后,有序公共事件不再向下一个订阅者传递。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 取消当前的有序公共事件。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//取消当前有序公共事件的回调 +function abortCB(err) { + if (err.code) { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCB); +``` + +## abortCommonEvent + +```ts +abortCommonEvent(): Promise +``` + +以Promise形式取消当前的有序公共事件,取消后,公共事件不再向下一个订阅者传递。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## clearAbortCommonEvent + +```ts +clearAbortCommonEvent(callback: AsyncCallback): void +``` + +以回调形式清除当前有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//清除当前公共事件取消状态的回调 +function clearAbortCB(err) { + if (err.code) { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCB); +``` + +## clearAbortCommonEvent + +```ts +clearAbortCommonEvent(): Promise +``` + +以Promise形式清除当前有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getAbortCommonEvent + +```ts +getAbortCommonEvent(callback: AsyncCallback): void +``` + +以回调形式获取当前有序公共事件是否取消的状态。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取当前有序公共事件是否取消的回调 +function getAbortCB(err, abortEvent) { + if (err.code) { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent " + abortEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCB); +``` + +## getAbortCommonEvent + +```ts +getAbortCommonEvent(): Promise +``` + +以Promise形式获取当前有序公共事件是否取消的状态。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ---------------------------------- | +| Promise\ | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.getAbortCommonEvent().then((abortEvent) => { + console.info("abortCommonEvent " + JSON.stringify(abortEvent)); +}).catch((err) => { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## getSubscribeInfo + +```ts +getSubscribeInfo(callback: AsyncCallback): void +``` + +以回调形式获取订阅者的订阅信息。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)> | 是 | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//获取订阅者信息回调 +function getCB(err, subscribeInfo) { + if (err.code) { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); + } +} +subscriber.getSubscribeInfo(getCB); +``` + +## getSubscribeInfo + +```ts +getSubscribeInfo(): Promise +``` + +以Promise形式获取订阅者的订阅信息。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)> | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.getSubscribeInfo().then((subscribeInfo) => { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); +}).catch((err) => { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); +}); +``` + +## finishCommonEvent9+ + +```ts +finishCommonEvent(callback: AsyncCallback): void +``` + +以回调形式结束当前有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | 是 | 表示有序公共事件结束后的回调函数。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +//结束当前有序公共事件的回调 +function finishCB(err) { + if (err.code) { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); +} else { + console.info("FinishCommonEvent"); +} + +subscriber.finishCommonEvent(finishCB); +``` + +## finishCommonEvent9+ + +```ts +finishCommonEvent(): Promise +``` + +以Promise形式结束当前有序公共事件。 + +**系统能力**:`SystemCapability.Notification.CommonEvent` + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +let subscriber; //创建成功的订阅者对象 + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md new file mode 100644 index 0000000000000000000000000000000000000000..d822600d6939bf2c981a1ddbd611d2d6672816ca --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md @@ -0,0 +1,16 @@ +# NotificationActionButton + +描述通知中显示的操作按钮。 + +> **说明:** +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | 是 | 是 | 按钮标题。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 点击按钮时触发的WantAgent。 | +| extras | { [key: string]: any } | 是 | 是 | 按钮扩展信息。 | +| userInput8+ | [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) | 是 | 是 | 用户输入对象实例。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md new file mode 100644 index 0000000000000000000000000000000000000000..5d3e7eee4755935751d1aaa1859fa16d3663197b --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md @@ -0,0 +1,16 @@ +# NotificationCommonDef + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## BundleOption + +BundleOption模块为指定应用的包信息。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ |---- | ------ | +| bundle | string | 是 | 应用的包信息。 | +| uid | number | 否 | 用户ID。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md new file mode 100644 index 0000000000000000000000000000000000000000..be8496b25a4909e2c7f2796e7e98c1381b50dfe1 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md @@ -0,0 +1,77 @@ +# NotificationContent + +描述通知类型。 + +> **说明:** +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](./js-apis-notificationManager.md#contenttype) | 是 | 是 | 通知内容类型。 | +| normal | [NotificationBasicContent](#notificationbasiccontent) | 是 | 是 | 基本类型通知内容。 | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | 是 | 是 | 长文本类型通知内容。 | +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | 是 | 是 | 多行类型通知内容。 | +| picture | [NotificationPictureContent](#notificationpicturecontent) | 是 | 是 | 图片类型通知内容。 | + +## NotificationBasicContent + +描述普通文本通知。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | 是 | 是 | 通知标题。 | +| text | string | 是 | 是 | 通知内容。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | + + +## NotificationLongTextContent + +描述长文本通知。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | 是 | 是 | 通知标题。 | +| text | string | 是 | 是 | 通知内容。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | +| longText | string | 是 | 是 | 通知的长文本。 | +| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | +| expandedTitle | string | 是 | 是 | 通知展开时的标题。 | + + +## NotificationMultiLineContent + +描述多行文本通知。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | 是 | 是 | 通知标题。 | +| text | string | 是 | 是 | 通知内容。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | +| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | +| longTitle | string | 是 | 是 | 通知展开时的标题。 | +| lines | Array\ | 是 | 是 | 通知的多行文本。 | + + +## NotificationPictureContent + +描述附有图片的通知。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | 是 | 是 | 通知标题。 | +| text | string | 是 | 是 | 通知内容。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | +| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | +| expandedTitle | string | 是 | 是 | 通知展开时的标题。 | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知的图片内容。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfc0990395386c786064be441c7c413d2fc744c --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md @@ -0,0 +1,29 @@ +# NotificationFlags + +描述通知标志的实例。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | 是 | 否 | 是否启用声音提示。 | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | 是 | 否 | 是否启用振动提醒功能。 | + + +## NotificationFlagStatus + +描述通知标志状态。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +**系统接口**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 值 | 说明 | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | 默认标志。 | +| TYPE_OPEN | 1 | 通知标志打开。 | +| TYPE_CLOSE | 2 | 通知标志关闭。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md new file mode 100644 index 0000000000000000000000000000000000000000..9c37ecd7a7fa595eb456796051157c62cf30ae68 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -0,0 +1,63 @@ +# NotificationRequest + +描述通知的请求。 + +> **说明:** +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | 是 | 是 | 通知内容。 | +| id | number | 是 | 是 | 通知ID。 | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | 是 | 是 | 通道类型。 | +| isOngoing | boolean | 是 | 是 | 是否进行时通知。 | +| isUnremovable | boolean | 是 | 是 | 是否可移除。 | +| deliveryTime | number | 是 | 是 | 通知发送时间。 | +| tapDismissed | boolean | 是 | 是 | 通知是否自动清除。 | +| autoDeletedTime | number | 是 | 是 | 自动清除的时间。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | +| extraInfo | {[key: string]: any} | 是 | 是 | 扩展参数。 | +| color | number | 是 | 是 | 通知背景颜色。预留能力,暂未支持。 | +| colorEnabled | boolean | 是 | 是 | 通知背景颜色是否使能。预留能力,暂未支持。 | +| isAlertOnce | boolean | 是 | 是 | 设置是否仅有一次此通知提醒。 | +| isStopwatch | boolean | 是 | 是 | 是否显示已用时间。 | +| isCountDown | boolean | 是 | 是 | 是否显示倒计时时间。 | +| isFloatingIcon | boolean | 是 | 是 | 是否显示状态栏图标。 | +| label | string | 是 | 是 | 通知标签。 | +| badgeIconStyle | number | 是 | 是 | 通知角标类型。 | +| showDeliveryTime | boolean | 是 | 是 | 是否显示分发时间。 | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | 是 | 是 | 通知按钮,最多三个按钮。 | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知小图标。可选字段,大小不超过30KB。 | +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知大图标。可选字段,大小不超过30KB。 | +| creatorBundleName | string | 是 | 否 | 创建通知的包名。 | +| creatorUid8+ | number | 是 | 否 | 创建通知的UID。 | +| creatorPid | number | 是 | 否 | 创建通知的PID。 | +| creatorUserId| number | 是 | 否 | 创建通知的UserId。 | +| hashCode | string | 是 | 否 | 通知唯一标识。 | +| classification | string | 是 | 是 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| groupName8+ | string | 是 | 是 | 组通知名称。 | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 是 | 是 | 通知模板。 | +| isRemoveAllowed8+ | boolean | 是 | 否 | 通知是否能被移除。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| source8+ | number | 是 | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| distributedOption8+ | [DistributedOptions](#distributedoptions) | 是 | 是 | 分布式通知的选项。 | +| deviceId8+ | string | 是 | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationflags#notificationFlags) | 是 | 否 | 获取NotificationFlags。 | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 当移除通知时,通知将被重定向到的WantAgent实例。 | +| badgeNumber9+ | number | 是 | 是 | 应用程序图标上显示的通知数。 | + + +## DistributedOptions + +描述分布式选项。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed8+ | boolean | 是 | 是 | 是否为分布式通知。 | +| supportDisplayDevices8+ | Array\ | 是 | 是 | 可以同步通知到的设备列表。 | +| supportOperateDevices8+ | Array\ | 是 | 是 | 可以打开通知的设备列表。 | +| remindType8+ | number | 是 | 否 | 通知的提醒方式。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md new file mode 100644 index 0000000000000000000000000000000000000000..27d5aec3672ee7caa0eefd640153f3ee70514a3a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md @@ -0,0 +1,24 @@ +# NotificationSlot + +描述通知槽 + +> **说明:** +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](js-apis-notificationManager.md#slottype) | 是 | 是 | 通道类型。 | +| level | number | 是 | 是 | 通知级别,不设置则根据通知渠道类型有默认值。 | +| desc | string | 是 | 是 | 通知渠道描述信息。 | +| badgeFlag | boolean | 是 | 是 | 是否显示角标。 | +| bypassDnd | boolean | 是 | 是 | 置是否在系统中绕过免打扰模式。 | +| lockscreenVisibility | number | 是 | 是 | 在锁定屏幕上显示通知的模式。 | +| vibrationEnabled | boolean | 是 | 是 | 是否可振动。 | +| sound | string | 是 | 是 | 通知提示音。 | +| lightEnabled | boolean | 是 | 是 | 是否闪灯。 | +| lightColor | number | 是 | 是 | 通知灯颜色。 | +| vibrationValues | Array\ | 是 | 是 | 通知振动样式。 | +| enabled9+ | boolean | 是 | 否 | 此通知插槽中的启停状态。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md new file mode 100644 index 0000000000000000000000000000000000000000..58e9d4442712e965f56d6837de8d9cbfef010544 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md @@ -0,0 +1,14 @@ +# NotificationTemplate + +通知模板。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ---------------------- | ---- | ---- | ---------- | +| name | string | 是 | 是 | 模板名称。 | +| data | {[key:string]: Object} | 是 | 是 | 模板数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md new file mode 100644 index 0000000000000000000000000000000000000000..bc60f868ba6d787cbacf2b79e50102b7f06cb103 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md @@ -0,0 +1,13 @@ +# NotificationUserInput + +保存用户输入的通知消息。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +**系统能力**:SystemCapability.Notification.Notification + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | 是 | 是 | 用户输入时用于标识此输入的key。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index 1633733d83c6688037a4614a2613a47543e03f94..263b4f1da9cb4ce51ee3449c806c1f65cc6ed95d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -51,7 +51,7 @@ this.context.destroy((err) => { ## InputMethodExtensionContext.destroy -destroy(): Promise; 停止输入法应用自身。通过Promise异步回调。 @@ -61,7 +61,7 @@ destroy(): Promise; | 无返回结果的Promise对象。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md index 454e533f1ee846fd3105c038cf69b98719578d7a..892b9a2b98717c5ec5e2e8f787bd79619e563f22 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -884,7 +884,7 @@ inputMethodController.off('selectByRange'); ### on('selectByMovement')10+ -on(type: 'selectByMovement', callback: Callback<Range>): void +on(type: 'selectByMovement', callback: Callback<Movement>): void 订阅输入法应用按光标动作选中文本事件。使用callback异步回调。 @@ -1235,8 +1235,6 @@ showOptionalInputMethods(callback: AsyncCallback<boolean>): void 显示输入法选择对话框。使用callback异步回调。 -**需要权限:** ohos.permission.CONNECT_IME_ABILITY,仅系统应用可用。 - **系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -1275,8 +1273,6 @@ showOptionalInputMethods(): Promise<boolean> 显示输入法选择对话框。使用promise异步回调。 -**需要权限:** ohos.permission.CONNECT_IME_ABILITY,仅系统应用可用。 - **系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md index 551562a61c610c300fc0c789ebd47b16a5f6dff9..85e09daf71de0b92629ef651c11fcab990a53af9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -708,7 +708,7 @@ hide(callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -742,7 +742,7 @@ hide(): Promise<void> | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -837,7 +837,7 @@ sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -886,7 +886,7 @@ sendKeyFunction(action: number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -928,7 +928,7 @@ getForward(length:number, callback: AsyncCallback<string>): void | 错误码ID | 错误信息 | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** @@ -974,7 +974,7 @@ getForward(length:number): Promise<string> | 错误码ID | 错误信息 | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** @@ -1013,7 +1013,7 @@ getBackward(length:number, callback: AsyncCallback<string>): void | 错误码ID | 错误信息 | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** @@ -1059,7 +1059,7 @@ getBackward(length:number): Promise<string> | 错误码ID | 错误信息 | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** @@ -1099,7 +1099,7 @@ deleteForward(length:number, callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1149,7 +1149,7 @@ deleteForward(length:number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1192,7 +1192,7 @@ deleteBackward(length:number, callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1242,7 +1242,7 @@ deleteBackward(length:number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1281,7 +1281,7 @@ insertText(text:string, callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1326,7 +1326,7 @@ insertText(text:string): Promise<boolean> | 错误码ID | 错误信息 | | -------- | -------------------------- | | 12800002 | Input method engine error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1366,7 +1366,7 @@ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1401,7 +1401,7 @@ getEditorAttribute(): Promise<EditorAttribute> | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1435,7 +1435,7 @@ moveCursor(direction: number, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1479,7 +1479,7 @@ moveCursor(direction: number): Promise<void> | 错误码ID | 错误信息 | | -------- | -------------------------- | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1517,7 +1517,7 @@ selectByRange(range: Range, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1562,7 +1562,7 @@ selectByRange(range: Range): Promise<void> | 错误码ID | 错误信息 | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1600,7 +1600,7 @@ selectByMovement(movement: Movement, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1620,7 +1620,7 @@ try { ### selectByMovement10+ -selectByMovement(range: Range): Promise<void> +selectByMovement(movement: Movement): Promise<void> 根据索引范围选中文本。使用promise异步回调。 @@ -1645,7 +1645,7 @@ selectByMovement(range: Range): Promise<void> | 错误码ID | 错误信息 | | -------- | -------------------------- | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | **示例:** @@ -1682,7 +1682,7 @@ getTextIndexAtCursor(callback: AsyncCallback<number>): void | 错误码ID | 错误信息 | | -------- | ------------------------------ | | 401 | parameter error. | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** @@ -1717,7 +1717,7 @@ getTextIndexAtCursor(): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md index dc3d93aabe3def9d5ec9b4e6efdbe13b941c43cf..07093fe9fbbf6ccb978ec1b64e8daa2adadabd71 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-installer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -118,6 +118,7 @@ install(hapFilePaths: Array<string>, installParam: InstallParam, callback: | 17700017 | Failed to install the HAP since the version of the HAP to install is too early. | | 17700018 | Failed to install because the dependent module does not exist. | | 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. | +| 17700036 | Failed to install because without allow app shared bundle permission. | **示例:** @@ -175,7 +176,6 @@ uninstall(bundleName: string, installParam: InstallParam, callback: AsyncCallbac | -------- | ------------------------------------------------------------ | | 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700101 | The system service is excepted. | **示例:** @@ -205,6 +205,119 @@ try { } ``` +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void ; + +以异步方法卸载一个共享包,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam) : Promise\; + +以异步方法卸载一个共享包,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------- | -------------------------------------- | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + ## BundleInstaller.recover recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback<void>): void; @@ -284,8 +397,22 @@ try { | 名称 | 类型 | 必填 | 说明 | | ------------------------------ | ------------------------------ | ------------------ | ------------------ | -| userId | number | 是 | 指示用户id,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9)获取当前进程所在用户。 | +| userId | number | 是 | 指示用户id,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId)获取当前进程所在用户。 | | installFlag | number | 是 | 指示安装标志,枚举值:0:应用初次安装,1:应用覆盖安装。 | | isKeepData | boolean | 是 | 卸载时是否保留数据目录。 | | hashParams | Array<[HashParam](#hashparam)> | 是 | 哈希值参数。 | -| crowdtestDeadline| number | 是 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期。 | \ No newline at end of file +| crowdtestDeadline| number | 是 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期。 | +| sharedBundleDirPaths | Array\ | 否 |共享包文件所在路径。 | + +## UninstallParam10+ + +共享包卸载需指定的参数信息。 + + **系统能力:** SystemCapability.BundleManager.BundleFramework.Core + + **系统接口:** 此接口为系统接口,三方应用不支持调用 + +| 名称 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 共享包包名。 | +| versionCode | number | 否 | 指示共享包的版本号。如果不填写versionCode,则卸载所有同版本共享包。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-intl.md b/zh-cn/application-dev/reference/apis/js-apis-intl.md index 584bd5b433ad8435b4c5067b4ec71823219bad56..1065a275779112f4950ce0c8316c02699444c798 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-intl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-intl.md @@ -67,7 +67,7 @@ constructor(locale: string, options?: LocaleOptions) | 参数名 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------- | ---- | ---------------------------- | | locale | string | 是 | 包含区域信息的字符串,包括语言以、脚本、国家或地区。语言、脚本、国家或地区的国际标准及组合方式请见[Intl开发指导](../../internationalization/intl-guidelines.md#设置区域信息) | -| options9+ | [LocaleOptions](#localeoptions6) | 否 | 用于创建区域对象的选项。 | +| options9+ | [LocaleOptions](#localeoptions9) | 否 | 用于创建区域对象的选项。 | **示例:** ```js @@ -159,7 +159,7 @@ minimize(): Locale ``` -## LocaleOptions6+ +## LocaleOptions9+ 表示区域初始化选项。 @@ -206,7 +206,7 @@ constructor(locale: string | Array<string>, options?: DateTimeOptions) | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | 是 | 包含区域设置信息的字符串,包括语言以及可选的脚本和区域。 | -| options9+ | [DateTimeOptions](#datetimeoptions6) | 否 | 用于创建时间日期格式化的选项。 | +| options9+ | [DateTimeOptions](#datetimeoptions9) | 否 | 用于创建时间日期格式化的选项。 | **示例:** ```js @@ -298,7 +298,7 @@ resolvedOptions(): DateTimeOptions | 类型 | 说明 | | ------------------------------------ | ----------------------------- | -| [DateTimeOptions](#datetimeoptions6) | DateTimeFormat 对象的格式化选项。 | +| [DateTimeOptions](#datetimeoptions9) | DateTimeFormat 对象的格式化选项。 | **示例:** ```js @@ -310,7 +310,7 @@ resolvedOptions(): DateTimeOptions ``` -## DateTimeOptions6+ +## DateTimeOptions9+ 表示时间日期格式化选项。 @@ -370,7 +370,7 @@ constructor(locale: string | Array<string>, options?: NumberOptions) | 参数名 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | 是 | 包含区域设置信息的字符串,包括语言以及可选的脚本和区域。 | -| options9+ | [NumberOptions](#numberoptions6) | 否 | 用于创建数字格式化的选项。 | +| options9+ | [NumberOptions](#numberoptions9) | 否 | 用于创建数字格式化的选项。 | **示例:** ```js @@ -420,7 +420,7 @@ resolvedOptions(): NumberOptions | 类型 | 说明 | | -------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions6) | NumberFormat 对象的格式化选项。 | +| [NumberOptions](#numberoptions9) | NumberFormat 对象的格式化选项。 | **示例:** @@ -433,7 +433,7 @@ resolvedOptions(): NumberOptions ``` -## NumberOptions6+ +## NumberOptions9+ 表示设备支持的能力。 @@ -493,7 +493,7 @@ constructor(locale: string | Array<string>, options?: CollatorOptions) | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | 是 | 包含区域设置信息的字符串,包括语言以及可选的脚本和区域。 | -| options9+ | [CollatorOptions](#collatoroptions8) | 否 | 用于创建排序对象的选项。 | +| options9+ | [CollatorOptions](#collatoroptions9) | 否 | 用于创建排序对象的选项。 | **示例:** ```js @@ -544,7 +544,7 @@ resolvedOptions(): CollatorOptions | 类型 | 说明 | | ------------------------------------ | ----------------- | -| [CollatorOptions](#collatoroptions8) | 返回的Collator对象的属性。 | +| [CollatorOptions](#collatoroptions9) | 返回的Collator对象的属性。 | **示例:** ```js @@ -556,7 +556,7 @@ resolvedOptions(): CollatorOptions ``` -## CollatorOptions8+ +## CollatorOptions9+ 表示Collator可设置的属性。 @@ -604,7 +604,7 @@ constructor(locale: string | Array<string>, options?: PluralRulesOptions) | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | 是 | 包含区域设置信息的字符串,包括语言以及可选的脚本和区域。 | -| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | 否 | 用于创建单复数对象的选项。 | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | 否 | 用于创建单复数对象的选项。 | **示例:** ```js @@ -647,7 +647,7 @@ select(n: number): string ``` -## PluralRulesOptions8+ +## PluralRulesOptions9+ 表示PluralRules对象可设置的属性。 @@ -695,7 +695,7 @@ constructor(locale: string | Array<string>, options?: RelativeTimeFormatIn | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | 是 | 包含区域设置信息的字符串,包括语言以及可选的脚本和区域。 | -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | 否 | 用于创建相对时间格式化对象的选项。 | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | 否 | 用于创建相对时间格式化对象的选项。 | **示例:** ```js @@ -787,7 +787,7 @@ resolvedOptions(): RelativeTimeFormatResolvedOptions ``` -## RelativeTimeFormatInputOptions8+ +## RelativeTimeFormatInputOptions9+ 表示RelativeTimeFormat对象可设置的属性。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-measure.md b/zh-cn/application-dev/reference/apis/js-apis-measure.md new file mode 100644 index 0000000000000000000000000000000000000000..07c24796a1f6325ba3cce2ae41fafe22cc565341 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-measure.md @@ -0,0 +1,128 @@ +# @ohos.measure (文本计算) + +本模块提供文本宽度、高度等相关计算。 + +> **说明** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import measure from '@ohos.measure' +``` + +## measure.measureText + +measureText(options: MeasureOptions): double + +计算指定文本单行布局下的宽度。 + +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------- | ---- | --------- | +| options | [MeasureOptions](#measureoptions) | 是 | 被计算文本描述信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------ | --------- | +| double | 文本宽度。
**说明:** 单位px。 | + + +**示例:** + +```ts +import measure from '@ohos.measure' +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + @State textWidth : number = measure.measureText({ + textContent: "Hello word", + fontSize: '50px' + }) + build() { + Row() { + Column() { + Text("The width of 'Hello World': " + this.textWidth) + } + .width('100%') + } + .height('100%') + } +} +``` + +## measure.measureTextSize10+ + +measureTextSize(options: MeasureOptions): SizeOptions + +计算指定文本单行布局下的宽度。 + +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------- | ---- | --------- | +| options | [MeasureOptions](#measureoptions) | 是 | 被计算文本描述信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------ | --------- | +| SizeOptions | 返回文本所占布局宽度和高度。
**说明:** 文本宽度以及高度返回值单位均为px。 | + + +**示例:** + +```ts +import measure from '@ohos.measure' +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + textSize : SizeOptions = measure.measureTextSize({ + textContent: "Hello word", + fontSize: '50px' + }) + build() { + Row() { + Column() { + Text("The width of 'Hello World': " + this.textSize.width) + Text("The height of 'Hello World': " + this.textSize.height) + } + .width('100%') + } + .height('100%') + } +} +``` + +## MeasureOptions + +被计算文本属性。 + +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + +| 名称 | 类型 | 必填 | 说明 | +| -------------- | -------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------- | +| textContent | string | 是 | 设置被计算文本内容。 | +| constraintWidth10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | 否 | 设置被计算文本布局宽度。
**说明:** 默认单位为vp | +| fontSize | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | 否 | 设置被计算文本字体大小,fontSize为number类型时,使用fp单位。
默认值:16fp。
**说明:** 不支持设置百分比字符串。 | +| fontStyle | number \| [FontStyle](../arkui-ts/ts-appendix-enums.md#fontstyle) | 否 | 设置被计算文本字体样式。
默认值:FontStyle.Normal | +| fontWeight | number \| string \| [FontWeight](../arkui-ts/ts-appendix-enums.md#fontweight) | 否 | 设置被计算文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。
默认值:FontWeight.Normal| +| fontFamily | string \| [Resource](../arkui-ts/ts-types.md#resource) | 否 | 设置被计算文本字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。| +| letterSpacing | number \| string | 否 | 设置被计算文本字符间距。| +| textAlign10+ | number \| [TextAlign](../arkui-ts/ts-appendix-enums.md#textalign) | 否 | 设置被计算文本水平方向的对齐方式。
默认值:TextAlign.Start| +| overflow10+ | number \| [TextOverflow](../arkui-ts/ts-appendix-enums.md#textoverflow) | 否 | 设置被计算文本超长时的截断方式。| +| maxLines10+ | number | 否 | 设置被计算文本最大行数。| +| lineHeight10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | 否 | 设置被计算文本行高。| +| baselineOffset10+ | number \| string | 否 | 设置被计算文本基线的偏移量。
默认值:0 | +| textCase10+ | number \| [TextCase](../arkui-ts/ts-appendix-enums.md#textcase) | 否 | 设置被计算文本大小写。
默认值:TextCase.Normal | + 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 25907d1fbcd5e36ef3450ac6174c7a815a6444fc..67763454ef51f5844a638f5310c4a3ba6ac8966a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -372,6 +372,10 @@ Audio/Video播放demo可参考:[AVPlayer开发指导](../../media/avplayer-pla | width9+ | number | 是 | 否 | 视频宽,单位为像素(px),可查询参数。
返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 | | height9+ | number | 是 | 否 | 视频高,单位为像素(px),可查询参数。
返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 | +**说明:** + +将资源句柄(fd)传递给媒体播放器之后,请不要通过该资源句柄做其他读写操作,包括但不限于将同一个资源句柄传递给多个媒体播放器。同一时间通过同一个资源句柄读写文件时存在竞争关系,将导致播放异常。 + ### on('stateChange')9+ on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void @@ -927,6 +931,14 @@ getTrackDescription(callback: AsyncCallback\>): void **示例:** ```js +printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + avPlayer.getTrackDescription((error, arrList) => { if ((arrList) != null) { for (let i = 0; i < arrList.length; i++) { @@ -964,6 +976,14 @@ getTrackDescription(): Promise\> ```js let arrayDescription; + +printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} avPlayer.getTrackDescription().then((arrList) => { if (arrList != null) { arrayDescription = arrList; @@ -1553,6 +1573,8 @@ on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void **示例:** ```js +import audio from '@ohos.multimedia.audio'; + avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { console.info('audioInterrupt success,and InterruptEvent info is:' + info) }) @@ -1754,7 +1776,7 @@ let AVRecorderConfig = { location : { latitude : 30, longitude : 130 } } -AVRecorder.prepare(AVRecorderConfig, (err) => { +avRecorder.prepare(AVRecorderConfig, (err) => { if (err == null) { console.info('prepare success'); } else { @@ -1825,7 +1847,7 @@ let AVRecorderConfig = { location : { latitude : 30, longitude : 130 } } -AVRecorder.prepare(AVRecorderConfig).then(() => { +avRecorder.prepare(AVRecorderConfig).then(() => { console.info('prepare success'); }).catch((err) => { console.info('prepare failed and catch error is ' + err.message); @@ -1866,7 +1888,7 @@ getInputSurface(callback: AsyncCallback\): void ```js let surfaceID = null; // 该surfaceID用于传递给相机接口创造videoOutput -AVRecorder.getInputSurface((err, surfaceId) => { +avRecorder.getInputSurface((err, surfaceId) => { if (err == null) { console.info('getInputSurface success'); surfaceID = surfaceId; @@ -1875,8 +1897,6 @@ AVRecorder.getInputSurface((err, surfaceId) => { } }); -// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); - ``` ### getInputSurface9+ @@ -1912,14 +1932,12 @@ getInputSurface(): Promise\ ```js let surfaceID = null; // 该surfaceID用于传递给相机接口创造videoOutput -AVRecorder.getInputSurface().then((surfaceId) => { +avRecorder.getInputSurface().then((surfaceId) => { console.info('getInputSurface success'); surfaceID = surfaceId; }).catch((err) => { console.info('getInputSurface failed and catch error is ' + err.message); }); - -// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); ``` ### start9+ @@ -1951,7 +1969,7 @@ start(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.start((err) => { +avRecorder.start((err) => { if (err == null) { console.info('start AVRecorder success'); } else { @@ -1989,7 +2007,7 @@ start(): Promise\ **示例:** ```js -AVRecorder.start().then(() => { +avRecorder.start().then(() => { console.info('start AVRecorder success'); }).catch((err) => { console.info('start AVRecorder failed and catch error is ' + err.message); @@ -2025,7 +2043,7 @@ pause(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.pause((err) => { +avRecorder.pause((err) => { if (err == null) { console.info('pause AVRecorder success'); } else { @@ -2063,7 +2081,7 @@ pause(): Promise\ **示例:** ```js -AVRecorder.pause().then(() => { +avRecorder.pause().then(() => { console.info('pause AVRecorder success'); }).catch((err) => { console.info('pause AVRecorder failed and catch error is ' + err.message); @@ -2099,7 +2117,7 @@ resume(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.resume((err) => { +avRecorder.resume((err) => { if (err == null) { console.info('resume AVRecorder success'); } else { @@ -2137,7 +2155,7 @@ resume(): Promise\ **示例:** ```js -AVRecorder.resume().then(() => { +avRecorder.resume().then(() => { console.info('resume AVRecorder success'); }).catch((err) => { console.info('resume AVRecorder failed and catch error is ' + err.message); @@ -2175,7 +2193,7 @@ stop(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.stop((err) => { +avRecorder.stop((err) => { if (err == null) { console.info('stop AVRecorder success'); } else { @@ -2215,7 +2233,7 @@ stop(): Promise\ **示例:** ```js -AVRecorder.stop().then(() => { +avRecorder.stop().then(() => { console.info('stop AVRecorder success'); }).catch((err) => { console.info('stop AVRecorder failed and catch error is ' + err.message); @@ -2250,7 +2268,7 @@ reset(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.reset((err) => { +avRecorder.reset((err) => { if (err == null) { console.info('reset AVRecorder success'); } else { @@ -2287,7 +2305,7 @@ reset(): Promise\ **示例:** ```js -AVRecorder.reset().then(() => { +avRecorder.reset().then(() => { console.info('reset AVRecorder success'); }).catch((err) => { console.info('reset AVRecorder failed and catch error is ' + err.message); @@ -2321,7 +2339,7 @@ release(callback: AsyncCallback\): void **示例:** ```js -AVRecorder.release((err) => { +avRecorder.release((err) => { if (err == null) { console.info('release AVRecorder success'); } else { @@ -2357,7 +2375,7 @@ release(): Promise\ **示例:** ```js -AVRecorder.release().then(() => { +avRecorder.release().then(() => { console.info('release AVRecorder success'); }).catch((err) => { console.info('release AVRecorder failed and catch error is ' + err.message); @@ -2382,9 +2400,8 @@ on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeRe **示例:** ```js -AVRecorder.on('stateChange', async (state, reason) => { +avRecorder.on('stateChange', async (state, reason) => { console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); - } }); ``` @@ -2405,7 +2422,7 @@ off(type: 'stateChange'): void **示例:** ```js -AVRecorder.off('stateChange'); +avRecorder.off('stateChange'); ``` ### on('error')9+ @@ -2437,7 +2454,7 @@ on(type: 'error', callback: ErrorCallback): void **示例:** ```js -AVRecorder.on('error', (err) => { +avRecorder.on('error', (err) => { console.info('case avRecorder.on(error) called, errMessage is ' + err.message); }); ``` @@ -2468,7 +2485,7 @@ off(type: 'error'): void **示例:** ```js -AVRecorder.off('error'); +avRecorder.off('error'); ``` ## AVRecorderState9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 752de65c1cb3089d882ca922587c05e2455a56f7..246d3418a2114a7e61ddef6227147087994cc6a3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,7 +1,10 @@ # @ohos.multimedia.medialibrary (媒体库管理) > **说明:** -> 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> - 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> - 从API Version 9开始废弃。保留至API Version 13版本。 +> - 部分功能变更为系统接口,仅供系统应用使用,请使用[@ohos.filemanagement.userFileManager](js-apis-userFileManager.md)相应接口替代。 +> - 媒体资源选择和保存功能仍开放给普通应用,请使用[@ohos.file.picker](js-apis-file-picker.md)相应接口替代。 ## 导入模块 ```js @@ -130,17 +133,12 @@ async function example() { console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); // 调用 getNextObject 接口获取下一个资源,直到最后一个 for (let i = 1; i < count; i++) { - fetchFileResult.getNextObject((error, fileAsset) => { - if (fileAsset == undefined) { - console.error('get next object failed with error: ' + error); - return; - } - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } + // 释放FetchFileResult实例并使其失效。无法调用其他方法 + fetchFileResult.close(); }); - // 释放FetchFileResult实例并使其失效。无法调用其他方法 - fetchFileResult.close(); }); } ``` @@ -198,18 +196,15 @@ async function example() { console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); // 调用 getNextObject 接口获取下一个资源,直到最后一个 for (let i = 1; i < count; i++) { - fetchFileResult.getNextObject().then((fileAsset) => { - console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }).catch((error) => { - console.error('get next object failed with error: ' + error); - }) + let fileAsset = await fetchFileResult.getNextObject(); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } + // 释放FetchFileResult实例并使其失效。无法调用其他方法 + fetchFileResult.close(); }).catch((error) => { // 调用getFirstObject接口失败 console.error('get first object failed with error: ' + error); }); - // 释放FetchFileResult实例并使其失效。无法调用其他方法 - fetchFileResult.close(); }).catch((error) => { // 调用getFileAssets接口失败 console.error('get file assets failed with error: ' + error); @@ -499,7 +494,7 @@ async function example() { ### getAlbums7+ -getAlbums(options: MediaFetchOptions, callback: AsyncCallback): void +getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album>>): void 获取相册列表,使用callback 方式返回结果。 @@ -534,7 +529,7 @@ async function example() { ### getAlbums7+ -getAlbums(options: MediaFetchOptions): Promise +getAlbums(options: MediaFetchOptions): Promise<Array<Album>> 获取相册列表,使用 promise 方式返回结果。 @@ -614,13 +609,13 @@ release(): Promise<void> media.release() ``` -### storeMediaAsset(deprecated) +### storeMediaAsset storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>): void 保存媒体资源,以异步方法获取保存成功的URI,使用callback形式返回结果。 -> **说明**: 从API Version 9开始废弃。 +> **说明**:此接口为API Version 6开始支持,只支持FA模型使用。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -650,13 +645,13 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => { ``` -### storeMediaAsset(deprecated) +### storeMediaAsset storeMediaAsset(option: MediaAssetOption): Promise<string> 保存媒体资源,以异步方法获取保存成功的URI,使用Promise形式返回结果。 -> **说明**: 从API Version 9开始废弃。 +> **说明**:此接口为API Version 6开始支持,只支持FA模型使用。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -689,13 +684,15 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): void 启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 -> **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 +> **说明**: +> 此接口为API Version 6开始支持,只支持FA模型使用。 +> 建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -731,13 +728,15 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => { ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void 启动图片预览界面,可以预览列表中首张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 -> **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 +> **说明**: +> 此接口为API Version 6开始支持,只支持FA模型使用。 +> 建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -771,13 +770,15 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => { ``` -### startImagePreview(deprecated) +### startImagePreview startImagePreview(images: Array<string>, index?: number): Promise<void> 启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用Promise方式进行异步回调。 -> **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 +> **说明**: +> 此接口为API Version 6开始支持,只支持FA模型使用。 +> 建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -816,13 +817,15 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { ``` -### startMediaSelect(deprecated) +### startMediaSelect startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array<string>>): void 启动媒体选择界面,以异步方法获取选择的媒体URI列表,使用callback形式返回结果。 -> **说明**:
从API Version 9开始废弃。建议使用系统应用图库替代。图库是系统内置的可视资源访问应用,提供图片和视频的管理、浏览等功能,使用方法请参考[OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos#4-%E5%85%B8%E5%9E%8B%E6%8E%A5%E5%8F%A3%E7%9A%84%E4%BD%BF%E7%94%A8)。 +> **说明**: +> 此接口为API Version 6开始支持,只支持FA模型使用。 +> 建议使用系统应用图库替代。图库是系统内置的可视资源访问应用,提供图片和视频的管理、浏览等功能,使用方法请参考[OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos#4-%E5%85%B8%E5%9E%8B%E6%8E%A5%E5%8F%A3%E7%9A%84%E4%BD%BF%E7%94%A8)。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -830,7 +833,7 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------------ | -| option | [MediaSelectOption](#mediaselectoptiondeprecated) | 是 | 媒体选择选项。 | +| option | [MediaSelectOption](#mediaselectoption) | 是 | 媒体选择选项。 | | callback | AsyncCallback<Array<string>> | 是 | 媒体选择回调,返回选择的媒体URI(datashare://)列表。 | **示例:** @@ -851,13 +854,15 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => { ``` -### startMediaSelect(deprecated) +### startMediaSelect startMediaSelect(option: MediaSelectOption): Promise<Array<string>> 启动媒体选择界面,以异步方法获取选择的媒体URI列表,使用Promise形式返回结果。 -> **说明**:
从API Version 9开始废弃。建议使用系统应用图库替代。图库是系统内置的可视资源访问应用,提供图片和视频的管理、浏览等功能,使用方法请参考[OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos#4-%E5%85%B8%E5%9E%8B%E6%8E%A5%E5%8F%A3%E7%9A%84%E4%BD%BF%E7%94%A8)。 +> **说明**: +> 此接口为API Version 6开始支持,只支持FA模型使用。 +> 建议使用系统应用图库替代。图库是系统内置的可视资源访问应用,提供图片和视频的管理、浏览等功能,使用方法请参考[OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos#4-%E5%85%B8%E5%9E%8B%E6%8E%A5%E5%8F%A3%E7%9A%84%E4%BD%BF%E7%94%A8)。 **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -865,7 +870,7 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> | 参数名 | 类型 | 必填 | 说明 | | ------ | --------------------------------------- | ---- | ------- | -| option | [MediaSelectOption](#mediaselectoptiondeprecated) | 是 | 媒体选择选项。 | +| option | [MediaSelectOption](#mediaselectoption) | 是 | 媒体选择选项。 | **返回值:** @@ -1907,9 +1912,9 @@ async function example() { if(i == fetchCount - 1) { var result = fetchFileResult.isAfterLast(); console.info('mediaLibrary fileAsset isAfterLast result: ' + result); + fetchFileResult.close(); } } - fetchFileResult.close(); } ``` @@ -1969,8 +1974,8 @@ async function example() { return; } console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName); + fetchFileResult.close(); }) - fetchFileResult.close(); } ``` @@ -2002,10 +2007,10 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getFirstObject().then((fileAsset) => { console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }).catch((error) => { console.error('getFirstObject failed with error: ' + error); }); - fetchFileResult.close(); } ``` @@ -2038,16 +2043,16 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fetchFileResult.isAfterLast) { + if (!fileAsset.isAfterLast) { fetchFileResult.getNextObject((error, fileAsset) => { if (error) { console.error('fetchFileResult getNextObject failed with error: ' + error); return; } console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }) } - fetchFileResult.close(); } ``` @@ -2081,14 +2086,14 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fetchFileResult.isAfterLast) { + if (!fileAsset.isAfterLast) { fetchFileResult.getNextObject().then((fileAsset) => { console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }).catch((error) => { console.error('fetchFileResult getNextObject failed with error: ' + error); }) } - fetchFileResult.close(); } ``` @@ -2124,8 +2129,8 @@ async function example() { return; } console.info('getLastObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }) - fetchFileResult.close(); } ``` @@ -2157,10 +2162,10 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getLastObject().then((fileAsset) => { console.info('getLastObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }).catch((error) => { console.error('getLastObject failed with error: ' + error); }); - fetchFileResult.close(); } ``` @@ -2197,8 +2202,8 @@ async function example() { return; } console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }) - fetchFileResult.close(); } ``` @@ -2236,10 +2241,10 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getPositionObject(0).then((fileAsset) => { console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName); + fetchFileResult.close(); }).catch((error) => { console.error('getPositionObject failed with error: ' + error); }); - fetchFileResult.close(); } ``` @@ -2276,9 +2281,9 @@ async function example() { } for (let i = 0; i < fetchFileResult.getCount(); i++) { console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName); - } + } + fetchFileResult.close(); }) - fetchFileResult.close(); } ``` @@ -2312,10 +2317,10 @@ async function example() { for (let i = 0; i < fetchFileResult.getCount(); i++) { console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName); } + fetchFileResult.close(); }).catch((error) => { console.error('getAllObject failed with error: ' + error); }); - fetchFileResult.close(); } ``` @@ -2447,10 +2452,10 @@ async function example() { console.error('album getFileAssets failed with error: ' + error); return; } - let count = fetchFileResult.getcount(); + let count = fetchFileResult.getCount(); console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); }); - fetchFileResult.close(); } ``` @@ -2484,7 +2489,7 @@ async function example() { selections: '', selectionArgs: [], }; - let fileNoArgsfetchOp = { + let fileNoArgsfetchOp = { selections: '', selectionArgs: [], }; @@ -2492,13 +2497,13 @@ async function example() { const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源 - album.getFileAssets(fileNoArgsfetchOp).then((albumFetchFileResult) => { - let count = fetchFileResult.getcount(); + album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { + let count = fetchFileResult.getCount(); console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); }).catch((error) => { console.error('album getFileAssets failed with error: ' + error); }); - fetchFileResult.close(); } ``` @@ -2622,12 +2627,10 @@ async function example() { | width | number | 是 | 是 | 宽(单位:像素) | | height | number | 是 | 是 | 高(单位:像素) | -## MediaAssetOption(deprecated) +## MediaAssetOption 媒体资源选项。 -> **说明**: 从API Version 9开始废弃。 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core @@ -2637,16 +2640,14 @@ async function example() { | mimeType | string | 是 | 是 | 媒体MIME(Multipurpose Internet Mail Extensions)类型。
包括:'image/\*'、'video/\*'、'audio/\*'、 'file\*'。 | | relativePath | string | 是 | 是 | 自定义媒体资源保存位置,例:Pictures/ 不填则保存到默认路径。
image类型默认路径Pictures/
video类型默认路径Videos/
audio类型默认路径Audios/
file类型默认路径Documents/ 。 | -## MediaSelectOption(deprecated) +## MediaSelectOption 媒体资源类型选项。 -> **说明**: 从API Version 9开始废弃。 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | ------ | ---- | ---- | -------------------- | | type | 'image' | 'video' | 'media' | 是 | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 | -| count | number | 是 | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 | +| count | number | 是 | 是 | 可以选择媒体数量的最大值,count = 1表示单选,count大于1表示多选。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index cfd1405bc9385985c34cee0500f6a82aa9e7cf98..585fb77a29c59dc7a361eb306c646879da8f6b09 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -1801,7 +1801,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络具体能力。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | @@ -1815,7 +1815,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 值 | 说明 | | --------------- | ---- | ----------- | @@ -1839,7 +1839,7 @@ connection.getDefaultNet().then(function (netHandle) { 提供承载数据网络能力的实例。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | @@ -1850,7 +1850,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络的能力集。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | --------------------- | ---------------------------------- | --- | ------------------------ | @@ -1863,7 +1863,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络连接信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ----|---------------- | @@ -1878,7 +1878,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络路由信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 |说明 | | -------------- | --------------------------- | --- |---------------- | @@ -1892,7 +1892,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络链路信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 |说明 | | ------------ | ----------------------- |---- |-------------------- | @@ -1903,7 +1903,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络地址。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | -- |------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md index 823f3f1aa66f05d8d518deeb7c6d43fcba681282..982f8ac0517be4ed950af8dd73504753a582ac3d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @@ -114,9 +114,9 @@ ethernet.setIfaceConfig("eth0", { dnsServers: "1.1.1.1", domain: "2.2.2.2" }).then(() => { - console.log("setIfaceConfig promiss ok "); + console.log("setIfaceConfig promise ok "); }).catch(error => { - console.log("setIfaceConfig promiss error = " + JSON.stringify(error)); + console.log("setIfaceConfig promise error = " + JSON.stringify(error)); }); ``` @@ -207,15 +207,15 @@ getIfaceConfig(iface: string): Promise\ ```js ethernet.getIfaceConfig("eth0").then((data) => { - console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode)); - console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr)); - console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route)); - console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway)); - console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask)); - console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers)); - console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain)); + console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode)); + console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr)); + console.log("getIfaceConfig promise route = " + JSON.stringify(data.route)); + console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); + console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); + console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); + console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain)); }).catch(error => { - console.log("getIfaceConfig promiss error = " + JSON.stringify(error)); + console.log("getIfaceConfig promise error = " + JSON.stringify(error)); }); ``` @@ -300,9 +300,9 @@ isIfaceActive(iface: string): Promise\ ```js ethernet.isIfaceActive("eth0").then((data) => { - console.log("isIfaceActive promiss = " + JSON.stringify(data)); + console.log("isIfaceActive promise = " + JSON.stringify(data)); }).catch(error => { - console.log("isIfaceActive promiss error = " + JSON.stringify(error)); + console.log("isIfaceActive promise error = " + JSON.stringify(error)); }); ``` @@ -377,12 +377,12 @@ getAllActiveIfaces(): Promise\> ```js ethernet.getAllActiveIfaces().then((data) => { - console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length)); + console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length)); for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i])); + console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i])); } }).catch(error => { - console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error)); + console.log("getAllActiveIfaces promise error = " + JSON.stringify(error)); }); ``` @@ -392,7 +392,7 @@ ethernet.getAllActiveIfaces().then((data) => { **系统接口**:此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Ethernet。 +**系统能力**:SystemCapability.Communication.NetManager.Ethernet | 名称 | 类型 | 必填 | 说明 | | ------------ | ----------------------- | ---|------------------------------------------------------------ | @@ -409,7 +409,7 @@ ethernet.getAllActiveIfaces().then((data) => { **系统接口**:此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Ethernet。 +**系统能力**:SystemCapability.Communication.NetManager.Ethernet | 名称 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md index a628c3346a7f923f1c170b340d922fa2336882bc..b585364ba9fcbd70b639acc858858a704d0c7ce9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -1479,7 +1479,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 后台网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | @@ -1492,7 +1492,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 计量网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 类型 | 说明 | | ----------------------- | ----------------------------------- | ------------------------------------------------------------ | @@ -1511,7 +1511,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 限制动作。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | @@ -1523,7 +1523,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 计量网络规则。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | @@ -1538,7 +1538,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 提醒类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | - | ------- | @@ -1549,7 +1549,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 应用对应的网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | 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 b9b5f24a3c572b586124b379039bca1eaa99cdb2..8b646e42f6042ec81666bd46964b9e802b059562 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -853,8 +853,8 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -883,8 +883,8 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ **示例:** ```js -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index 804b78251304dccae0f08e9d9a88565b65ac794e..c1c30a09a349303b3daaa6c28f8df9216421a066 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -24,7 +24,7 @@ publish(request: NotificationRequest, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | | callback | AsyncCallback\ | 是 | 发布通知的回调方法。 | **错误码:** @@ -78,7 +78,7 @@ publish(request: NotificationRequest): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | **错误码:** @@ -130,7 +130,7 @@ publish(request: NotificationRequest, userId: number, callback: AsyncCallback\ | 是 | 被指定的回调方法。 | @@ -192,7 +192,7 @@ publish(request: NotificationRequest, userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | | userId | number | 是 | 用户ID。 | **错误码:** @@ -427,7 +427,7 @@ addSlot(slot: NotificationSlot, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| slot | [NotificationSlot](#notificationslot) | 是 | 要创建的通知通道对象。 | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 要创建的通知通道对象。 | | callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | **错误码:** @@ -474,7 +474,7 @@ addSlot(slot: NotificationSlot): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ---- | ---------------- | ---- | -------------------- | -| slot | [NotificationSlot](#notificationslot) | 是 | 要创建的通知通道对象。 | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 要创建的通知通道对象。 | **错误码:** @@ -585,7 +585,7 @@ addSlots(slots: Array\, callback: AsyncCallback\): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------ | -| slots | Array\<[NotificationSlot](#notificationslot)\> | 是 | 要创建的通知通道对象数组。 | +| slots | Array\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | 是 | 要创建的通知通道对象数组。 | | callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | **错误码:** @@ -636,7 +636,7 @@ addSlots(slots: Array\): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ----- | ------------------------- | ---- | ------------------------ | -| slots | Array\<[NotificationSlot](#notificationslot)\> | 是 | 要创建的通知通道对象数组。 | +| slots | Array\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | 是 | 要创建的通知通道对象数组。 | **错误码:** @@ -677,7 +677,7 @@ getSlot(slotType: SlotType, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | | slotType | [SlotType](#slottype) | 是 | 通知渠道类型,目前分为社交通信、服务提醒、内容咨询和其他类型。 | -| callback | AsyncCallback\<[NotificationSlot](#notificationslot)\> | 是 | 表示被指定的回调方法。 | +| callback | AsyncCallback\<[NotificationSlot](js-apis-inner-notification-notificationSlot.md)\> | 是 | 表示被指定的回调方法。 | **错误码:** @@ -757,7 +757,7 @@ getSlots(callback: AsyncCallback>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | -------------------- | -| callback | AsyncCallback\\> | 是 | 以callback形式返回获取此应用程序的所有通知通道的结果。 | +| callback | AsyncCallback\\> | 是 | 以callback形式返回获取此应用程序的所有通知通道的结果。 | **错误码:** @@ -793,7 +793,7 @@ getSlots(): Promise\> | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\\> | 以Promise形式返回获取此应用程序的所有通知通道的结果。 | +| Promise\\> | 以Promise形式返回获取此应用程序的所有通知通道的结果。 | **错误码:** @@ -965,7 +965,7 @@ setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | | callback | AsyncCallback\ | 是 | 设定通知使能回调函数。 | @@ -1012,7 +1012,7 @@ setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | **错误码:** @@ -1053,7 +1053,7 @@ isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 获取通知使能状态回调函数。 | **错误码:** @@ -1099,7 +1099,7 @@ isNotificationEnabled(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** @@ -1187,7 +1187,7 @@ isNotificationEnabled(): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** @@ -1230,7 +1230,7 @@ displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\ | 是 | 设定角标使能回调函数。 | @@ -1277,7 +1277,7 @@ displayBadge(bundle: BundleOption, enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | **错误码:** @@ -1318,7 +1318,7 @@ isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 获取角标使能状态回调函数。 | **错误码:** @@ -1364,7 +1364,7 @@ isBadgeDisplayed(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** @@ -1483,8 +1483,8 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | -| slot | [NotificationSlot](#notificationslot) | 是 | 通知通道。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 通知通道。 | | callback | AsyncCallback\ | 是 | 设定通知通道回调函数。 | **错误码:** @@ -1533,8 +1533,8 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | -| slot | [NotificationSlot](#notificationslot) | 是 | 通知通道。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 通知通道。 | **错误码:** @@ -1577,8 +1577,8 @@ getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback> | 是 | 获取通知通道回调函数。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | +| callback | AsyncCallback> | 是 | 获取通知通道回调函数。 | **错误码:** @@ -1623,13 +1623,13 @@ getSlotsByBundle(bundle: BundleOption): Promise> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise> | 以Promise形式返回获取指定应用的通知通道。 | +| Promise> | 以Promise形式返回获取指定应用的通知通道。 | **错误码:** @@ -1669,7 +1669,7 @@ getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 获取通知通道数量回调函数。 | **错误码:** @@ -1715,7 +1715,7 @@ getSlotNumByBundle(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** @@ -1762,7 +1762,7 @@ getAllActiveNotifications(callback: AsyncCallback>) | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | -------------------- | -| callback | AsyncCallback> | 是 | 获取活动通知回调函数。 | +| callback | AsyncCallback> | 是 | 获取活动通知回调函数。 | **错误码:** @@ -1788,7 +1788,7 @@ notificationManager.getAllActiveNotifications(getAllActiveNotificationsCallback) ## notificationManager.getAllActiveNotifications -getAllActiveNotifications(): Promise\\> +getAllActiveNotifications(): Promise\\> 获取当前未删除的所有通知(Promise形式)。 @@ -1802,7 +1802,7 @@ getAllActiveNotifications(): Promise\\> | 以Promise形式返回获取活动通知。 | +| Promise\\> | 以Promise形式返回获取活动通知。 | **错误码:** @@ -1904,7 +1904,7 @@ getActiveNotifications(callback: AsyncCallback>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback> | 是 | 获取当前应用通知列表回调函数。 | +| callback | AsyncCallback> | 是 | 获取当前应用通知列表回调函数。 | **错误码:** @@ -1932,7 +1932,7 @@ notificationManager.getActiveNotifications(getActiveNotificationsCallback); ## notificationManager.getActiveNotifications -getActiveNotifications(): Promise\\> +getActiveNotifications(): Promise\\> 获取当前应用未删除的通知列表(Promise形式)。 @@ -1942,7 +1942,7 @@ getActiveNotifications(): Promise\\> | 以Promise形式返回获取当前应用通知列表。 | +| Promise\\> | 以Promise形式返回获取当前应用通知列表。 | **错误码:** @@ -1974,7 +1974,7 @@ cancelGroup(groupName: string, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------- | -| groupName | string | 是 | 通知组名称,此名称需要在发布通知时通过[NotificationRequest](#notificationrequest)对象指定。 | +| groupName | string | 是 | 通知组名称,此名称需要在发布通知时通过[NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest)对象指定。 | | callback | AsyncCallback\ | 是 | 取消本应用指定组下通知的回调函数。 | **错误码:** @@ -2052,7 +2052,7 @@ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | groupName | string | 是 | 通知组名称。 | | callback | AsyncCallback\ | 是 | 删除指定应用指定组下通知的回调函数。 | @@ -2100,7 +2100,7 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------ | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | groupName | string | 是 | 通知组名称。 | **错误码:** @@ -2743,7 +2743,7 @@ setDistributedEnable(enable: boolean, callback: AsyncCallback\): void **示例:** ```javascript -function setDistributedEnableCallback() { +function setDistributedEnableCallback(err) { if (err) { console.error(`setDistributedEnable failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2888,7 +2888,7 @@ setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: As | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | enable | boolean | 是 | 是否支持。 | | callback | AsyncCallback\ | 是 | 应用程序是否支持分布式通知的回调函数。 | @@ -2942,7 +2942,7 @@ setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise\ | 是 | 查询指定应用是否支持分布式通知的回调函数。 | **错误码:** @@ -3005,7 +3005,7 @@ isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包。 | **返回值:** @@ -3164,7 +3164,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | | representativeBundle | string | 是 | 被代理应用的包名。 | | userId | number | 是 | 用户ID。 | | callback | AsyncCallback | 是 | 发布代理通知的回调方法。 | @@ -3231,7 +3231,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | | representativeBundle | string | 是 | 被代理应用的包名。 | | userId | number | 是 | 用户ID。 | @@ -3391,7 +3391,7 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | type | [SlotType](#slottype) | 是 | 指定渠道类型。 | | enable | boolean | 是 | 使能状态。 | | callback | AsyncCallback\ | 是 | 设置渠道使能回调函数。 | @@ -3442,7 +3442,7 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean) | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | type | [SlotType](#slottype) | 是 | 渠道类型。 | | enable | boolean | 是 | 使能状态。 | @@ -3485,7 +3485,7 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncC | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 应用的包信息。 | | type | [SlotType](#slottype) | 是 | 渠道类型。 | | callback | AsyncCallback\ | 是 | 获取渠道使能状态回调函数。 | @@ -3534,7 +3534,7 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ | LEVEL_HIGH | 4 | 表示通知功能已启用,状态栏中显示通知图标,有横幅和提示音。 | -## BundleOption - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ |---- | --- | ------ | -| bundle | string | 是 | 是 | 应用的包信息。 | -| uid | number | 是 | 是 | 用户ID。 | - - ## SlotType **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification @@ -3832,227 +3822,6 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => | OTHER_TYPES | 0xFFFF | 其他类型。 | -## NotificationActionButton - -描述通知中显示的操作按钮。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | -| title | string | 是 | 是 | 按钮标题。 | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 点击按钮时触发的WantAgent。 | -| extras | { [key: string]: any } | 是 | 是 | 按钮扩展信息。 | -| userInput | [NotificationUserInput](#notificationuserinput) | 是 | 是 | 用户输入对象实例。 | - - -## NotificationBasicContent - -描述普通文本通知。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------- | ------ | ---- | ---- | ---------------------------------- | -| title | string | 是 | 是 | 通知标题。 | -| text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | - - -## NotificationLongTextContent - -描述长文本通知。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------- | ------ | ---- | --- | -------------------------------- | -| title | string | 是 | 是 | 通知标题。 | -| text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | -| longText | string | 是 | 是 | 通知的长文本。 | -| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | -| expandedTitle | string | 是 | 是 | 通知展开时的标题。 | - - -## NotificationMultiLineContent - -描述多行文本通知。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------- | --------------- | --- | --- | -------------------------------- | -| title | string | 是 | 是 | 通知标题。 | -| text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | -| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | -| longTitle | string | 是 | 是 | 通知展开时的标题。 | -| lines | Array\ | 是 | 是 | 通知的多行文本。 | - - -## NotificationPictureContent - -描述附有图片的通知。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------- | -------------- | ---- | --- | -------------------------------- | -| title | string | 是 | 是 | 通知标题。 | -| text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | -| briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | -| expandedTitle | string | 是 | 是 | 通知展开时的标题。 | -| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知的图片内容。 | - - -## NotificationContent - -描述通知类型。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | -| contentType | [ContentType](#contenttype) | 是 | 是 | 通知内容类型。 | -| normal | [NotificationBasicContent](#notificationbasiccontent) | 是 | 是 | 基本类型通知内容。 | -| longText | [NotificationLongTextContent](#notificationlongtextcontent) | 是 | 是 | 长文本类型通知内容。 | -| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | 是 | 是 | 多行类型通知内容。 | -| picture | [NotificationPictureContent](#notificationpicturecontent) | 是 | 是 | 图片类型通知内容。 | - - -## NotificationFlagStatus - -描述通知标志状态。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统接口**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 值 | 说明 | -| -------------- | --- | --------------------------------- | -| TYPE_NONE | 0 | 默认标志。 | -| TYPE_OPEN | 1 | 通知标志打开。 | -| TYPE_CLOSE | 2 | 通知标志关闭。 | - - -## NotificationFlags - -描述通知标志的实例。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | -| soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | 是 | 否 | 是否启用声音提示。 | -| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | 是 | 否 | 是否启用振动提醒功能。 | - - -## NotificationRequest - -描述通知的请求。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | -| content | [NotificationContent](#notificationcontent) | 是 | 是 | 通知内容。 | -| id | number | 是 | 是 | 通知ID。 | -| slotType | [SlotType](#slottype) | 是 | 是 | 通道类型。 | -| isOngoing | boolean | 是 | 是 | 是否进行时通知。 | -| isUnremovable | boolean | 是 | 是 | 是否可移除。 | -| deliveryTime | number | 是 | 是 | 通知发送时间。 | -| tapDismissed | boolean | 是 | 是 | 通知是否自动清除。 | -| autoDeletedTime | number | 是 | 是 | 自动清除的时间。 | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | -| extraInfo | {[key: string]: any} | 是 | 是 | 扩展参数。 | -| color | number | 是 | 是 | 通知背景颜色。预留能力,暂未支持。 | -| colorEnabled | boolean | 是 | 是 | 通知背景颜色是否使能。预留能力,暂未支持。 | -| isAlertOnce | boolean | 是 | 是 | 设置是否仅有一次此通知提醒。 | -| isStopwatch | boolean | 是 | 是 | 是否显示已用时间。 | -| isCountDown | boolean | 是 | 是 | 是否显示倒计时时间。 | -| isFloatingIcon | boolean | 是 | 是 | 是否显示状态栏图标。 | -| label | string | 是 | 是 | 通知标签。 | -| badgeIconStyle | number | 是 | 是 | 通知角标类型。 | -| showDeliveryTime | boolean | 是 | 是 | 是否显示分发时间。 | -| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | 是 | 是 | 通知按钮,最多三个按钮。 | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知小图标。可选字段,大小不超过30KB。 | -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知大图标。可选字段,大小不超过30KB。 | -| creatorBundleName | string | 是 | 否 | 创建通知的包名。 | -| creatorUid | number | 是 | 否 | 创建通知的UID。 | -| creatorPid | number | 是 | 否 | 创建通知的PID。 | -| creatorUserId| number | 是 | 否 | 创建通知的UserId。 | -| hashCode | string | 是 | 否 | 通知唯一标识。 | -| classification | string | 是 | 是 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| groupName| string | 是 | 是 | 组通知名称。 | -| template | [NotificationTemplate](#notificationtemplate) | 是 | 是 | 通知模板。 | -| isRemoveAllowed | boolean | 是 | 否 | 通知是否能被移除。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| source | number | 是 | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| distributedOption | [DistributedOptions](#distributedoptions) | 是 | 是 | 分布式通知的选项。 | -| deviceId | string | 是 | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| notificationFlags | [NotificationFlags](#notificationflags) | 是 | 否 | 获取NotificationFlags。 | -| removalWantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 当移除通知时,通知将被重定向到的WantAgent实例。 | -| badgeNumber | number | 是 | 是 | 应用程序图标上显示的通知数。 | - - -## DistributedOptions - -描述分布式选项。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | -| isDistributed | boolean | 是 | 是 | 是否为分布式通知。 | -| supportDisplayDevices | Array\ | 是 | 是 | 可以同步通知到的设备列表。 | -| supportOperateDevices | Array\ | 是 | 是 | 可以打开通知的设备列表。 | -| remindType | number | 是 | 否 | 通知的提醒方式。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | - - -## NotificationSlot - -描述通知槽 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | -| type | [SlotType](#slottype) | 是 | 是 | 通道类型。 | -| level | number | 是 | 是 | 通知级别,不设置则根据通知渠道类型有默认值。 | -| desc | string | 是 | 是 | 通知渠道描述信息。 | -| badgeFlag | boolean | 是 | 是 | 是否显示角标。 | -| bypassDnd | boolean | 是 | 是 | 置是否在系统中绕过免打扰模式。 | -| lockscreenVisibility | number | 是 | 是 | 在锁定屏幕上显示通知的模式。 | -| vibrationEnabled | boolean | 是 | 是 | 是否可振动。 | -| sound | string | 是 | 是 | 通知提示音。 | -| lightEnabled | boolean | 是 | 是 | 是否闪灯。 | -| lightColor | number | 是 | 是 | 通知灯颜色。 | -| vibrationValues | Array\ | 是 | 是 | 通知振动样式。 | -| enabled9+ | boolean | 是 | 否 | 此通知插槽中的启停状态。 | - - -## NotificationTemplate - -通知模板。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ---- | ---------------------- | ---- | ---- | ---------- | -| name | string | 是 | 是 | 模板名称。 | -| data | {[key:string]: Object} | 是 | 是 | 模板数据。 | - - -## NotificationUserInput - -保存用户输入的通知消息。 - -**系统能力**:SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | ------ | --- | ---- | ----------------------------- | -| inputKey | string | 是 | 是 | 用户输入时用于标识此输入的key。 | ## DeviceRemindType diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md index 868c70f3f7828b5d55fba84f489b460be9cef06e..cfc61dacf914744662371b7530e785f3d0e97474 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -30,8 +30,8 @@ subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, c | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 是 | 通知订阅信息。 | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | +| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | 是 | 通知订阅信息。 | | callback | AsyncCallback\ | 是 | 订阅动作回调函数。 | **错误码:** @@ -83,7 +83,7 @@ subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | | callback | AsyncCallback\ | 是 | 订阅动作回调函数。 | **错误码:** @@ -133,8 +133,8 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 否 | 通知订阅信息。 | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | +| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | 否 | 通知订阅信息。 | **错误码:** @@ -178,7 +178,7 @@ unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------- | ---- | -------------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | | callback | AsyncCallback\ | 是 | 取消订阅动作回调函数。 | **错误码:** @@ -201,8 +201,8 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -226,7 +226,7 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | +| subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | **错误码:** @@ -241,8 +241,8 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ **示例:** ```js -function onDisconnectCallback(data) { - console.info("Cancel callback: " + JSON.stringify(data)); +function onDisconnectCallback() { + console.info("subscribe disconnect"); } let subscriber = { onDisconnect: onDisconnectCallback @@ -268,8 +268,8 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 参数名 | 类型 | 必填 | 说明 | | --------------- | ----------------------------------| ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | -| notificationKey | [NotificationKey](#notificationkey) | 是 | 通知键值。 | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | +| notificationKey | [NotificationKey](js-apis-notification.md#notificationkey) | 是 | 通知键值。 | | reason | [RemoveReason](#removereason) | 是 | 通知删除原因。 | | callback | AsyncCallback\ | 是 | 删除指定通知回调函数。 | @@ -324,8 +324,8 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 参数名 | 类型 | 必填 | 说明 | | --------------- | --------------- | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | -| notificationKey | [NotificationKey](#notificationkey) | 是 | 通知键值。 | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 是 | 指定应用的包信息。 | +| notificationKey | [NotificationKey]((js-apis-notification.md#notificationkey)) | 是 | 通知键值。 | | reason | [RemoveReason](#removereason) | 是 | 通知删除原因。 | **错误码:** @@ -372,7 +372,7 @@ remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | 是 | 通知唯一ID。可以通过[onConsume](#onconsume)回调的入参[SubscribeCallbackData](#subscribecallbackdata)获取其内部[NotificationRequest](#notificationrequest)对象中的hashCode。 | +| hashCode | string | 是 | 通知唯一ID。可以通过[onConsume](#onconsume)回调的入参[SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)获取其内部[NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest)对象中的hashCode。 | | reason | [RemoveReason](#removereason) | 是 | 通知删除原因。 | | callback | AsyncCallback\ | 是 | 删除指定通知回调函数。 | @@ -459,7 +459,7 @@ removeAll(bundle: BundleOption, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 删除指定应用的所有通知回调函数。 | **错误码:** @@ -547,7 +547,7 @@ removeAll(bundle?: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 否 | 指定应用的包信息。 | +| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | 否 | 指定应用的包信息。 | **错误码:** @@ -668,7 +668,7 @@ notificationSubscribe.removeAll(userId, removeAllCallback); ### onConsume -onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void +onConsume?: (data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void 接收到新通知的回调函数。 @@ -680,7 +680,7 @@ onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 新接收到的通知信息。 | +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | 是 | 新接收到的通知信息。 | **示例:** @@ -708,7 +708,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onCancel -onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void +onCancel?:(data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void 取消通知的回调函数。 @@ -720,7 +720,7 @@ onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 需要取消的通知信息。 | +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | 是 | 需要取消的通知信息。 | **示例:** @@ -748,7 +748,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onUpdate -onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void +onUpdate?:(data: [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) => void 更新通知排序的回调函数。 @@ -760,7 +760,7 @@ onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](#notificationsortingmap) | 是 | 最新的通知排序列表。 | +| data | [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) | 是 | 最新的通知排序列表。 | **示例:** @@ -935,7 +935,7 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); ### onEnabledNotificationChanged -onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata)) => void +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata)) => void 监听应用通知使能变化。 @@ -947,7 +947,7 @@ onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](# | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata)\> | 是 | 回调返回监听到的应用信息。 | +| callback | AsyncCallback\<[EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata)\> | 是 | 回调返回监听到的应用信息。 | **示例:** @@ -1013,104 +1013,6 @@ let subscriber = { notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` -## BundleOption - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ |---- | --- | ------ | -| bundle | string | 是 | 是 | 应用的包信息。 | -| uid | number | 是 | 是 | 用户ID。 | - -## NotificationKey - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----- | ------ | ---- | --- | -------- | -| id | number | 是 | 是 | 通知ID。 | -| label | string | 是 | 是 | 通知标签。 | - -## SubscribeCallbackData - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------------- | ------------------------------------------------- | -------- | -------- | -------- | -| request | [NotificationRequest](js-apis-notificationManager.md#notificationrequest) | 是 | 否 | 通知内容。 | -| sortingMap | [NotificationSortingMap](#notificationsortingmap) | 是 | 否 | 排序信息。 | -| reason | number | 是 | 否 | 删除原因。 | -| sound | string | 是 | 否 | 通知声音。 | -| vibrationValues | Array\ | 是 | 否 | 通知震动。 | - - -## EnabledNotificationCallbackData - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 描述 | -| ------ | ------- | ---------------- | ---------------- | ---------------- | -| bundle | string | 是 | 否 | 应用的包名。 | -| uid | number | 是 | 否 | 应用的uid。 | -| enable | boolean | 是 | 否 | 应用通知使能状态。 | - - -## NotificationSorting - -提供有关活动通知的排序信息。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | ------------------------------------- | ---- | --- | ------------ | -| slot | [NotificationSlot](js-apis-notificationManager.md#notificationslot) | 是 | 否 | 通知通道内容。 | -| hashCode | string | 是 | 否 | 通知唯一标识。 | -| ranking | number | 是 | 否 | 通知排序序号。 | - - -## NotificationSortingMap - -提供关于已订阅的所有通知中活动通知的排序信息 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | -| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | 是 | 否 | 通知排序信息数组。 | -| sortedHashCode | Array\ | 是 | 否 | 通知唯一标识数组。 | - - -## NotificationSubscribeInfo - -设置订阅所需通知的发布者的信息。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----------- | --------------- | --- | ---- | ------------------------------- | -| bundleNames | Array\ | 是 | 是 | 指定订阅哪些包名的APP发来的通知。 | -| userId | number | 是 | 是 | 指定订阅哪个用户下发来的通知。 | - - -## NotificationUserInput - -保存用户输入的通知消息。 - -**系统能力**:SystemCapability.Notification.Notification - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | ------ | --- | ---- | ----------------------------- | -| inputKey | string | 是 | 是 | 用户输入时用于标识此输入的key。 | ## RemoveReason diff --git a/zh-cn/application-dev/reference/apis/js-apis-observer.md b/zh-cn/application-dev/reference/apis/js-apis-observer.md index f3d1b051fc1eab8f70b8af83f950ae70427582ec..fc56ac2dc9d8935be77b809436822a1d8b1f4d41 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-observer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-observer.md @@ -10,7 +10,7 @@ ## 导入模块 ``` -import observer from '@ohos.telephony.observer' +import observer from '@ohos.telephony.observer'; ``` ## observer.on('networkStateChange') @@ -44,7 +44,7 @@ on\(type: \'networkStateChange\', callback: Callback\): void; **示例:** ```js -observer.on('networkStateChange', data =>{ +observer.on('networkStateChange', data => { console.log("on networkStateChange, data:" + JSON.stringify(data)); }); ``` @@ -82,7 +82,7 @@ on\(type: \'networkStateChange\', options: { slotId: number }, callback: Callbac **示例:** ```js -observer.on('networkStateChange', {slotId: 0}, data =>{ +observer.on('networkStateChange', {slotId: 0}, data => { console.log("on networkStateChange, data:" + JSON.stringify(data)); }); ``` @@ -156,7 +156,7 @@ on\(type: \'signalInfoChange\', callback: Callback\>): **示例:** ```js -observer.on('signalInfoChange', data =>{ +observer.on('signalInfoChange', data => { console.log("on signalInfoChange, data:" + JSON.stringify(data)); }); ``` @@ -192,7 +192,7 @@ on\(type: \'signalInfoChange\', options: { slotId: number }, callback: Callback< **示例:** ```js -observer.on('signalInfoChange', {slotId: 0}, data =>{ +observer.on('signalInfoChange', {slotId: 0}, data => { console.log("on signalInfoChange, data:" + JSON.stringify(data)); }); ``` @@ -239,6 +239,125 @@ observer.off('signalInfoChange', callback); observer.off('signalInfoChange'); ``` +## observer.on('cellInfoChange')8+ + +on\(type: \'cellInfoChange\', callback: Callback\): void; + +订阅小区信息变化事件,使用callback方式作为异步方法。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION + +**系统能力**:SystemCapability.Telephony.StateRegistry + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | ---- |------------------------------------------------------------| +| type | string | 是 | 小区信息变化事件,固定为'cellInfoChange'。 | +| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | 是 | 回调函数。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +observer.on('cellInfoChange', data => { + console.log("on cellInfoChange, data:" + JSON.stringify(data)); +}); +``` + + +## observer.on('cellInfoChange')8+ + +on\(type: \'cellInfoChange\', options: { slotId: number }, callback: Callback\): void; + +订阅指定卡槽位的小区信息变化事件,使用callback方式作为异步方法。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION + +**系统能力**:SystemCapability.Telephony.StateRegistry + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ |--------------------------------------------------| ---- |------------------------------------------------------------| +| type | string | 是 | 小区信息变化事件,固定为'cellInfoChange'。 | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | +| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | 是 | 回调函数。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +observer.on('cellInfoChange', {slotId: 0}, data => { + console.log("on cellInfoChange, data:" + JSON.stringify(data)); +}); +``` + + +## observer.off('cellInfoChange')8+ + +off\(type: \'cellInfoChange\', callback?: Callback\): void; + +取消订阅小区信息变化事件,使用callback方式作为异步方法。 + +>**说明:** +> +>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 + +**系统接口:** 此接口为系统接口。 + +**系统能力**:SystemCapability.Telephony.StateRegistry + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 小区信息变化事件,固定为'cellInfoChange'。 | +| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | 否 | 回调函数。| + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let callback = data => { + console.log("on cellInfoChange, data:" + JSON.stringify(data)); +} +observer.on('cellInfoChange', callback); +// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +observer.off('cellInfoChange', callback); +observer.off('cellInfoChange'); +``` ## observer.on('callStateChange') @@ -268,7 +387,7 @@ on(type: 'callStateChange', callback: Callback\<{ state: CallState, number: stri **示例:** ```js -observer.on('callStateChange', value =>{ +observer.on('callStateChange', value => { console.log("on callStateChange, state:" + value.state + ", number:" + value.number); }); ``` @@ -303,7 +422,7 @@ on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ st **示例:** ```js -observer.on('callStateChange', {slotId: 0}, value =>{ +observer.on('callStateChange', {slotId: 0}, value => { console.log("on callStateChange, state:" + value.state + ", number:" + value.number); }); ``` @@ -379,7 +498,7 @@ on\(type: 'cellularDataConnectionStateChange', callback: Callback\<{ state: Data **示例:** ```js -observer.on('cellularDataConnectionStateChange', value =>{ +observer.on('cellularDataConnectionStateChange', value => { console.log("on cellularDataConnectionStateChange, state:" + value.state + ", network:" + value.network); }); ``` @@ -414,7 +533,7 @@ on\(type: 'cellularDataConnectionStateChange', options: { slotId: number }, call **示例:** ```js -observer.on('cellularDataConnectionStateChange', {slotId: 0}, value =>{ +observer.on('cellularDataConnectionStateChange', {slotId: 0}, value => { console.log("on cellularDataConnectionStateChange, state:" + value.state + ", network:" + value.network); }); ``` @@ -490,7 +609,7 @@ on\(type: 'cellularDataFlowChange', callback: Callback\\): void; **示例:** ```js -observer.on('cellularDataFlowChange', data =>{ +observer.on('cellularDataFlowChange', data => { console.log("on networkStateChange, data:" + JSON.stringify(data)); }); ``` @@ -525,7 +644,7 @@ on\(type: 'cellularDataFlowChange', options: { slotId: number }, callback: Call **示例:** ```js -observer.on('cellularDataFlowChange', {slotId: 0}, data =>{ +observer.on('cellularDataFlowChange', {slotId: 0}, data => { console.log("on cellularDataFlowChange, data:" + JSON.stringify(data)); }); ``` @@ -601,7 +720,7 @@ on\(type: 'simStateChange', callback: Callback\\): void; **示例:** ```js -observer.on('simStateChange', data =>{ +observer.on('simStateChange', data => { console.log("on simStateChange, data:" + JSON.stringify(data)); }); ``` @@ -636,7 +755,7 @@ on\(type: 'simStateChange', options: { slotId: number }, callback: Callback\{ +observer.on('simStateChange', {slotId: 0}, data => { console.log("on simStateChange, data:" + JSON.stringify(data)); }); ``` @@ -688,7 +807,7 @@ observer.off('simStateChange'); SIM卡锁类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.StateRegistry。 +**系统能力**:SystemCapability.Telephony.StateRegistry | 名称 | 值 | 说明 | | ----------- | ---- | ----------------- | @@ -711,11 +830,10 @@ SIM卡锁类型。 SIM卡类型和状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.StateRegistry。 +**系统能力**:SystemCapability.Telephony.StateRegistry | 名称 | 类型 | 必填 | 说明 | | ------------------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| type | [CardType](js-apis-sim.md#cardtype) | 是 | SIM卡类型,参考sim的[CardType](js-apis-sim.md#cardtype)。 | -| state | [SimState](js-apis-sim.md#simstate) | 是 | SIM卡状态,参考sim的[SimState](js-apis-sim.md#simstate)。 | +| type | [CardType](js-apis-sim.md#cardtype7) | 是 | SIM卡类型。 | +| state | [SimState](js-apis-sim.md#simstate) | 是 | SIM卡状态。 | | reason8+ | [LockReason](#lockreason8) | 是 | SIM卡锁类型。 | - diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index e2a3d4ccd66b3feb6572fcb77ffdad6a390cea9f..b99b134d6a67d8eb2ddb534ad5b76a8682527a1e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -326,9 +326,9 @@ checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: A | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId or constraint. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 @@ -376,9 +376,9 @@ checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise< | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId or constraint. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 @@ -475,8 +475,6 @@ checkOsAccountVerified(callback: AsyncCallback<boolean>): void 检查当前系统帐号是否已验证。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS - **系统能力:** SystemCapability.Account.OsAccount **参数:** @@ -489,9 +487,7 @@ checkOsAccountVerified(callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | **示例:** @@ -531,9 +527,9 @@ checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -555,7 +551,7 @@ checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): ### checkOsAccountVerified9+ -checkOsAccountVerified(localId?: number): Promise<boolean> +checkOsAccountVerified(localId: number): Promise<boolean> 检查指定系统帐号是否已验证。使用Promise异步回调。 @@ -567,7 +563,7 @@ checkOsAccountVerified(localId?: number): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | --------------------------------------------------------------- | -| localId | number | 否 | 系统帐号ID。不填则检查当前系统帐号是否已验证。 | +| localId | number | 是 | 系统帐号ID。不填则检查当前系统帐号是否已验证。 | **返回值:** @@ -579,9 +575,9 @@ checkOsAccountVerified(localId?: number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -991,7 +987,7 @@ getOsAccountLocalId(callback: AsyncCallback<number>): void | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | +| 12300001 | system service exception. | **示例:** @@ -1028,7 +1024,7 @@ getOsAccountLocalId(): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | +| 12300001 | system service exception. | **示例:** @@ -1064,8 +1060,8 @@ getOsAccountLocalIdForUid(uid: number, callback: AsyncCallback<number>): v | 错误码ID | 错误信息 | | -------- | --------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid uid. | +| 12300001 | system service exception. | +| 12300002 | invalid uid. | **示例:** 查询值为12345678的uid所属的系统帐号的帐号ID @@ -1108,8 +1104,8 @@ getOsAccountLocalIdForUid(uid: number): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid uid. | +| 12300001 | system service exception. | +| 12300002 | invalid uid. | **示例:** 查询值为12345678的uid所属的系统帐号ID @@ -1148,8 +1144,8 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallb | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid domainInfo. | +| 12300001 | system service exception. | +| 12300002 | invalid domainInfo. | **示例:** @@ -1195,8 +1191,8 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise<number&g | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid domainInfo. | +| 12300001 | system service exception. | +| 12300002 | invalid domainInfo. | **示例:** @@ -1474,7 +1470,7 @@ getActivatedOsAccountLocalIds(callback: AsyncCallback<Array<number>> | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | +| 12300001 | system service exception. | **示例:** @@ -1511,7 +1507,7 @@ getActivatedOsAccountLocalIds(): Promise<Array<number>> | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | +| 12300001 | system service exception. | **示例:** @@ -2233,9 +2229,9 @@ getOsAccountLocalIdForSerialNumber(serialNumber: number, callback: AsyncCallback | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid serialNumber. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid serialNumber. | +| 12300003 | the account indicated by serialNumber dose not exist. | **示例:** 查询与SN码12345关联的系统帐号的ID @@ -2276,9 +2272,9 @@ getOsAccountLocalIdForSerialNumber(serialNumber: number): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid serialNumber. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid serialNumber. | +| 12300003 | the account indicated by serialNumber dose not exist. | **示例:** 查询与SN码12345关联的系统帐号的ID @@ -2315,9 +2311,9 @@ getSerialNumberForOsAccountLocalId(localId: number, callback: AsyncCallback<n | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** 获取ID为100的系统帐号关联的SN码 @@ -2358,9 +2354,9 @@ getSerialNumberForOsAccountLocalId(localId: number): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid localId. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** 获取ID为100的系统帐号关联的SN码 @@ -2483,8 +2479,8 @@ getBundleIdForUid(uid: number, callback: AsyncCallback<number>): void; | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid uid. | +| 12300001 | system service exception. | +| 12300002 | invalid uid. | **示例:** @@ -2526,8 +2522,8 @@ getBundleIdForUid(uid: number): Promise<number>; | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid uid. | +| 12300001 | system service exception. | +| 12300002 | invalid uid. | **示例:** @@ -2644,9 +2640,9 @@ getOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId or constraint. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid name or constraint. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -2691,9 +2687,9 @@ getOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise& | 错误码ID | 错误信息 | | -------- | ------------- | -| 12300001 | System service exception. | -| 12300002 | Invalid localId or constraint. | -| 12300003 | Account not found. | +| 12300001 | system service exception. | +| 12300002 | invalid name or constraint. | +| 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -4433,15 +4429,26 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs **示例:** ```js let plugin = { - auth: (domainInfo, credential, callback) => { + auth: (domainAccountInfo, credential, callback) => { // mock authentication - callback.onResult(0, {}); - } + // notify authentication result + callback.onResult(0, { + token: new Uint8Array([0]), + remainTimes: 5, + freezingTime: 0 + }); + }, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin); let userAuth = new account_osAccount.UserAuth(); let challenge = new Uint8Array([0]); - let authType = account_osAccount.AuthType.PIN; + let authType = account_osAccount.AuthType.DOMAIN; let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; try { userAuth.auth(challenge, authType, authTrustLevel, { @@ -4455,6 +4462,235 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs } ``` +### authWithPopup10+ + +authWithPopup(domainAccountInfo: DomainAccountInfo, callback: IUserAuthCallback): void + +弹窗认证指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 指示认证结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => { + // mock authentication + // notify authentication result + callback.onResult(0, { + token: new Uint8Array([0]), + remainTimes: 5, + freezingTime: 0 + }); + }, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + +### authWithToken10+ + +authWithToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, callback: IUserAuthCallback): void + +使用授权令牌认证指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| token | Uint8Array | 是 | 指示PIN码或生物识别认证成功时生成的授权令牌。| +| callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 指示认证结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => { + // mock authentication + // notify authentication result + callback.onResult(0, { + token: new Uint8Array([0]), + remainTimes: 5, + freezingTime: 0 + }); + }, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + +### getAccountInfo10+ + +getAccountInfo(domain: string, accountName: string, callback: AsyncCallback<DomainAccountInfo>): void + +查询指定域帐号的信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domain | string | 是 | 指示帐号所属域。| +| accountName | string | 是 | 指示帐号的名称。| +| callback | AsyncCallback<[DomainAccountInfo](#domainaccountinfo8)> | 是 | 指示查询结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => { + // mock getting account information + // notify result + callback({ + code: 0 + }, { + domain: domain, + accountName: accountName, + accountId: "xxxx" + }) + }, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + +### getAuthStatusInfo10+ + +getAuthStatusInfo(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<AuthStatusInfo>): void + +查询指定域帐号的认证状态信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| callback | AsyncCallback<[AuthStatusInfo](#authstatusinfo10)> | 是 | 指示查询结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => { + callback({ + code: 0 + }, { + remainTimes: 5, + freezingTime: 0 + }) + }, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + +### bindAccount10+ + +bindAccount(domainAccountInfo: DomainAccountInfo, localId: number, callback: AsyncCallback<void>): void + +绑定指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| callback | AsyncCallback<void> | 是 | 指示绑定结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => { + // mock unbinding operation + // notify binding result + callback({code: 0}) + }, + unbindAccount: (domainAccountInfo, callback) => {} + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + +### unbindAccount10+ + +unbindAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<void>): void + +解绑指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| callback | AsyncCallback<void> | 是 | 指示绑定结果回调。| + +**示例:** + ```js + let plugin = { + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => { + // mock unbinding operation + // notify unbinding result + callback({code: 0}) + } + } + account_osAccount.DomainAccountManager.registerPlugin(plugin) + ``` + ## DomainAccountManager 9+ 域帐号管理器类。 @@ -4480,15 +4716,18 @@ static registerPlugin(plugin: DomainPlugin): void | 错误码ID | 错误信息 | | -------- | --------------------------- | -| 12300201 | The domain plugin has been registered. | +| 12300201 | the domain plugin has been registered. | **示例:** ```js let plugin = { - auth: (domainInfo, credential, callback) => { - // mock authentication - callback.onResult(0, {}); - } + auth: (domainAccountInfo, credential, callback) => {}, + authWithPopup: (domainAccountInfo, callback) => {}, + authWithToken: (domainAccountInfo, callback) => {}, + getAccountInfo: (domain, accountName, callback) => {}, + getAuthStatusInfo: (domainAccountInfo, callback) => {}, + bindAccount: (domainAccountInfo, localId, callback) => {}, + unbindAccount: (domainAccountInfo, callback) => {} } try { account_osAccount.DomainAccountManager.registerPlugin(plugin); @@ -4520,6 +4759,252 @@ static unregisterPlugin(): void } ``` +### auth10+ + +auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUserAuthCallback): void + +认证指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**需要权限:** ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| credential | Uint8Array | 是 | 指示域帐号的凭据。| +| callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 指示认证结果回调。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | system service exception. | +| 12300002 | invalid domainAccountInfo or credential. | +| 12300003 | domain account does not exist. | +| 12300013 | network exception. | +| 12300101 | authentication failed. | +| 12300109 | authentication is canceled. | +| 12300110 | authentication is locked. | +| 12300111 | authentication timeout. | +| 12300112 | authentication service is busy. | +| 12300113 | authentication service does not exist. | +| 12300114 | authentication service exception. | + +**示例:** + ```js + let domainAccountInfo = { + domain: "CHINA", + accountName: "zhangsan" + } + let credential = new Uint8Array([0]) + try { + account_osAccount.DomainAccountManager.auth(domainAccountInfo, credential, { + onResult: (resultCode, authResult) => { + console.log('auth resultCode = ' + resultCode); + console.log('auth authResult = ' + JSON.stringify(authResult)); + } + }); + } catch (err) { + console.log('auth exception = ' + JSON.stringify(err)); + } + ``` + +### authWithPopup10+ + +authWithPopup(callback: IUserAuthCallback): void + +弹框认证指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**需要权限:** ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 指示认证结果回调。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | system service exception. | +| 12300003 | no domain account is bound. | +| 12300013 | network exception. | +| 12300101 | authentication failed. | +| 12300109 | authentication is canceled. | +| 12300110 | authentication is locked. | +| 12300111 | authentication timeout. | +| 12300112 | authentication service is busy. | +| 12300113 | authentication service does not exist. | +| 12300114 | authentication service exception. | + +**示例:** + ```js + try { + account_osAccount.DomainAccountManager.authWithPopup({ + onResult: (resultCode, authResult) => { + console.log('auth resultCode = ' + resultCode); + console.log('auth authResult = ' + JSON.stringify(authResult)); + } + }) + } catch (err) { + console.log('auth exception = ' + JSON.stringify(err)); + } + ``` + +### authWithPopup10+ + +authWithPopup(localId: number, callback: IUserAuthCallback): void + +弹框认证指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**需要权限:** ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| localId | number | 是 | 指示绑定域帐号的系统帐号的本地标识。| +| callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 指示认证结果回调。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | system service exception. | +| 12300002 | invalid localId. | +| 12300003 | no domain account is bound. | +| 12300013 | network exception. | +| 12300101 | authentication failed. | +| 12300109 | authentication is canceled. | +| 12300110 | authentication is locked. | +| 12300111 | authentication timeout. | +| 12300112 | authentication service is busy. | +| 12300113 | authentication service does not exist. | +| 12300114 | authentication service exception. | + +**示例:** + ```js + try { + account_osAccount.DomainAccountManager.authWithPopup(100, { + onResult: (resultCode, authResult) => { + console.log('authWithPopup resultCode = ' + resultCode); + console.log('authWithPopup authResult = ' + JSON.stringify(authResult)); + } + }) + } catch (err) { + console.log('authWithPopup exception = ' + JSON.stringify(err)); + } + ``` + +### hasAccount10+ + +hasAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<boolean>): void + +检查是否存在指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| +| callback | AsyncCallback<boolean> | 是 | 指示检查结果回调。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | system service exception. | +| 12300002 | invalid domainAccountInfo. | +| 12300013 | network exception. | + +**示例:** + ```js + let domainAccountInfo = { + domain: "CHINA", + accountName: "zhangsan" + } + try { + account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo, (err, result) => { + if (err) { + console.log("call hasAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("hasAccount result: " + result); + } + }); + } catch (err) { + console.log('hasAccount exception = ' + JSON.stringify(err)); + } + ``` + +### hasAccount10+ + +hasAccount(domainAccountInfo: DomainAccountInfo): Promise<boolean> + +检查是否存在指定的域帐号。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Account.OsAccount + +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 指示域帐号信息。| + +**返回值:** + +| 类型 | 说明 | +| :------------------------ | ----------------------- | +| Promise<boolean> | Promise对象,返回指定的域帐号是否存在。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | system service exception. | +| 12300002 | invalid domainAccountInfo. | +| 12300013 | network exception. | + +**示例:** + ```js + let domainAccountInfo = { + domain: "CHINA", + accountName: "zhangsan" + } + try { + account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((result) => { + console.log("hasAccount result: " + result); + }).catch((err) => { + console.log("call hasAccount failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log('hasAccount exception = ' + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ 获取用户身份管理类。 @@ -5254,7 +5739,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | ------------ | ---------------------------------------- | ----- | ----------------- | | result | number | 是 | 指示结果。 | | authSubType | [AuthSubType](#authsubtype8) | 是 | 指示认证凭据子类型。| -| remainTimes | number | 否 | 指示剩余时间。 | +| remainTimes | number | 否 | 指示剩余次数。 | | freezingTime | number | 否 | 指示冻结时间。 | ## AuthResult8+ @@ -5268,7 +5753,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | 名称 | 类型 | 必填 | 说明 | | ------------ | ----------- | ----- | ----------------- | | token | Uint8Array | 否 | 指示认证令牌。 | -| remainTimes | number | 否 | 指示剩余时间。 | +| remainTimes | number | 否 | 指示剩余次数。 | | freezingTime | number | 否 | 指示冻结时间。 | ## CredentialInfo8+ @@ -5351,7 +5836,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | PIN | 1 | 表示PIN认证类型。 | | FACE | 2 | 表示脸部认证类型。| | FINGERPRINT10+ | 4 | 表示指纹认证类型。 | -| DOMAIN10+ | 1024 | 表示域认证类型。| +| DOMAIN9+ | 1024 | 表示域认证类型。| ## AuthSubType8+ @@ -5368,7 +5853,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | PIN_MIXED | 10002 | 表示自定义混合凭据。 | | FACE_2D | 20000 | 表示2D 人脸凭证。 | | FACE_3D | 20001 | 表示3D 人脸凭证。 | -| DOMAIN_MIXED10+ | 10240001 | 表示域认证混合凭证。 | +| DOMAIN_MIXED9+ | 10240001 | 表示域认证混合凭证。 | ## AuthTrustLevel8+ @@ -5490,6 +5975,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | ----------- | ------ | ---- | ---------- | | domain | string | 是 | 域名。 | | accountName | string | 是 | 域帐号名。 | +| accountId10+ | string | 否 | 域帐号标识。 | ## 系统帐号约束列表 @@ -5585,4 +6071,17 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | CONSTRAINT_NOT_EXIST | 0 | 约束不存在 | | CONSTRAINT_TYPE_BASE | 1 | 约束源自系统设置 | | CONSTRAINT_TYPE_DEVICE_OWNER | 2 | 约束源自设备所有者设置 | -| CONSTRAINT_TYPE_PROFILE_OWNER | 3 | 约束源自资料所有者设置 | \ No newline at end of file +| CONSTRAINT_TYPE_PROFILE_OWNER | 3 | 约束源自资料所有者设置 | + +## AuthStatusInfo10+ + +表示认证状态信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.OsAccount。 + +| 名称 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------- | +| remainTimes | number | 是 | 剩余次数 | +| freezingTime | number | 是 | 冻结时间 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-overlay.md b/zh-cn/application-dev/reference/apis/js-apis-overlay.md new file mode 100755 index 0000000000000000000000000000000000000000..0d14da22d3ec2677e626d7f086242ad5af5ca3d5 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-overlay.md @@ -0,0 +1,693 @@ +# @ohos.bundle.overlay (overlay模块) + +本模块提供[overlay特征应用](#overlay特征应用介绍)的安装,overlay特征应用的[OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md)信息的查询以及overlay特征应用的禁用使能的能力。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## 导入模块 + +``` ts +import overlay from '@ohos.bundle.overlay' +``` + +## overlay.setOverlayEnabled + +setOverlayEnabled(moduleName:string, isEnabled: boolean): Promise\; + +以异步方法设置当前应用中overlay特征module的禁用使能状态。使用Promise异步回调。成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | 是 | overlay特征module的HAP名称。 | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var moduleName = "feature"; +var isEnabled = false; + +try { + overlay.setOverlayEnabled(moduleName, isEnabled) + .then(() => { + console.info('setOverlayEnabled success'); + }).catch((error) => { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }); +} catch (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabled + +setOverlayEnabled(moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void; + +以异步方法设置当前应用中overlay module的禁用使能状态。使用callback异步回调。成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | 是 | overlay特征module的HAP名称。 | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。| +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var moduleName = "feature"; +var isEnabled = false; + +try { + overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => { + if (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + return; + } + console.info('setOverlayEnabled success'); + }); +} catch (error) { + console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabledByBundleName + +setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean): Promise\; + +以异步方法设置指定应用的overlay module的禁用使能状态。使用Promise异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.CHANGE_OVERLAY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | 是 | 指定应用的bundle名称。 | +| moduleName | string | 是 | 指定应用的overlay module的HAP名称。 | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" +var isEnabled = false; + +try { + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) + .then((data) => { + console.info('setOverlayEnabledByBundleName successfully'); + }).catch((error) => { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }); +} catch (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.setOverlayEnabledByBundleName + +setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void; + +以异步方法设置指定应用的overlay module的禁用使能状态。使用callback异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.CHANGE_OVERLAY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | 是 | 指定应用的bundle名称。 | +| moduleName | string | 是 | 指定应用的overlay特征module的HAP名称。 | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 | +| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" +var isEnabled = false; + +try { + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => { + if (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + return; + } + console.info('setOverlayEnabledByBundleName successfully'); + }); +} catch (error) { + console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} +``` + +## overlay.getOverlayModuleInfo + +getOverlayModuleInfo(moduleName: string): Promise\; + +以异步方法获取当前应用中指定的module的overlayModuleInfo信息。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ------------------------------------------ | +| moduleName | string | 是 | 指定当前应用中的overlay module的HAP名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象,无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName); + console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo)); + } catch(err) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getOverlayModuleInfo + +getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\): void; + +以异步方法获取当前应用中指定的module的overlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| moduleName | string | 是 | 指定当前应用中的overlay特征module的HAP名称。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var moduleName = "feature" +try { + overlay.getOverlayModuleInfo(moduleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfos + +getTargetOverlayModuleInfos(targetModuleName: string): Promise\>; + +以异步方法获取指定的目标module的OverlayModuleInfo。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| targetModuleName | string | 是 | 指定当前应用中的目标module的HAP名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\> | Promise对象,无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | + +**示例:** + +```ts +var targetModuleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getTargetOverlayModuleInfos + +getTargetOverlayModuleInfos(targetModuleName: string, callback: AsyncCallback\>): void; + +以异步方法获取指定的目标module的OverlayModuleInfo。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| targetModuleName | string | 是 | 指定当前应用中的目标module的HAP名称。 | +| callback | AsyncCallback\> | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | + +**示例:** + +```ts +var targetModuleName = "feature" +try { + overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promise\>; + +以异步方法获取指定应用中指定module的OverlayModuleInfo信息。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | 是 | 指定应用的bundle名称。 | +| moduleName | string | 否 | 指定应用中的overlay module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module的OverlayModuleInfo信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\> | Promise对象,无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callback: AsyncCallback\>): void; + +以异步方法获取指定应用中指定module的OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | 是 | 指定应用的bundle名称。 | +| moduleName | string | 是 | 指定应用中的overlay module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module的OverlayModuleInfo信息。 | +| callback | AsyncCallback\> | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +try { + overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getOverlayModuleInfoByBundleName + +getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\>): void; + +以异步方法获取指定应用中所有module的OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | 是 | 指定应用的bundle名称。 | +| callback | AsyncCallback\> | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700032 | The specified bundleName does not contain any overlay module. | +| 17700033 | The specified moduleName is not overlay module. | + +**示例:** + +```ts +var bundleName = "com.example.myapplication_xxxxx"; + +try { + overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => { + if (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: string): Promise\>; + +以异步方法获取指定应用中指定module关联的所有OverlayModuleInfo信息。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | 是 | 指定目标应用的bundle名称。 | +| moduleName | string | 否 | 指定应用中的目标module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module所关联的OverlayModuleInfo信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\> | Promise对象,无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**示例:** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +(async() => { + try { + let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName); + console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); + } catch(err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + } +})(); +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\>): void; + +以异步方法获取指定应用中指定module关联的所有OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | 是 | 指定目标应用的bundle名称。 | +| moduleName | string | 否 | 指定应用中的目标module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module所关联的OverlayModuleInfo信息。 | +| callback | AsyncCallback\> | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**示例:** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; +var moduleName = "feature" + +try { + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay.getTargetOverlayModuleInfosByBundleName + +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\>): void; + +以异步方法获取指定应用中所有module关联的所有OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Overlay + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| targetBundleName | string | 是 | 指定目标应用的bundle名称。 | +| callback | AsyncCallback\> | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not existed. | +| 17700034 | The specified moduleName is overlay module. | +| 17700035 | The specified bundleName is overlay bundle. | + +**示例:** + +```ts +var targetBundleName = "com.example.myapplication_xxxxx"; + +try { + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => { + if (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + return; + } + console.log('overlayModuleInfo is ' + JSON.stringify(data)); + }); +} catch (error) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} +``` + +## overlay特征应用介绍 + +**概念** +overlay特征应用指的是应用中包含有overlay特征的module。该特征module一般是为设备上存在的非overlay特征的module提供额外的资源文件,以便于目标module在运行阶段可以使用这些额外的资源文件来展示不同的颜色,标签,主题等等。overlay特征仅适用与stage模型。 + +**如何识别overlay特征的module** +在IDE中创建应用工程时, module的配置文件module.json5中包含targetModuleName和targetPriority字段时,该module将会在安装阶段被识别为overlay特征的module。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md index 8c47f29f71e8bc20fed17d4f270fd445a01cefe3..146d48f1fcd41709301bfcaf20548a36e892e180 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @@ -606,7 +606,7 @@ let opt = { scaleMode: 1 }; image.createPixelMap(buffer, opt).then((pixelMap) => { - let pasteData = pasteboard.createData(MIMETYPE_PIXELMAP, pixelMap); + let pasteData = pasteboard.createData(pasteboard.MIMETYPE_PIXELMAP, pixelMap); let PixelMap = pasteData.getPrimaryPixelMap(); }); ``` @@ -782,7 +782,7 @@ getRecord(index: number): PasteDataRecord | 错误码ID | 错误信息 | | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **示例:** @@ -880,7 +880,7 @@ removeRecord(index: number): void | 错误码ID | 错误信息 | | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **示例:** @@ -910,7 +910,7 @@ replaceRecord(index: number, record: PasteDataRecord): void | 错误码ID | 错误信息 | | -------- | -------- | -| 12900001 | The index is out of range. | +| 12900001 | The index is out of the record. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md index 1eae91fc9ae92b7a9082ae4a66692a45a77ddf73..948eb9a341774b3d717489f6b80a0136966716b5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -14,7 +14,7 @@ | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | 是 | 否 | 用户传入的权限。| -| authResults | Array<number> | 是 | 否 | 相应请求权限的结果:
-1表示权限已设置,无需弹窗,需要用户在"设置"中修改。
0表示无需任何操作。
1表示需要动态弹窗授权。
2表示请求无效,可能原因有:
-未在设置文件中声明目标权限;
-权限名非法;
-部分权限存在特殊申请条件,在申请对应权限时未满足其指定的条件,见[ohos.permission.LOCATION](../../security/permission-list.md#ohospermissionlocation)与[ohos.permission.APPROXIMATELY_LOCATION](../../security/permission-list.md#ohospermissionapproximately_location)| +| authResults | Array<number> | 是 | 否 | 相应请求权限的结果:
- -1:未授权,表示权限已设置,无需弹窗,需要用户在"设置"中修改。
- 0:已授权。
- 2:未授权,表示请求无效,可能原因有:
-未在设置文件中声明目标权限。
-权限名非法。
-部分权限存在特殊申请条件,在申请对应权限时未满足其指定的条件,见[ohos.permission.LOCATION](../../security/permission-list.md#ohospermissionlocation)与[ohos.permission.APPROXIMATELY_LOCATION](../../security/permission-list.md#ohospermissionapproximately_location) | ## 使用说明 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 04918ca06f0759a4033d73afcfb769861dcbecc5..a8abc368b6b5652bdc11d892ae2b22db21d6f647 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -45,7 +45,7 @@ addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCou | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the count value is invalid. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100007 | Service is abnormal. | @@ -95,7 +95,7 @@ addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCou | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, or the count value is invalid. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100007 | Service is abnormal. | @@ -266,7 +266,7 @@ startUsingPermission(tokenID: number, permissionName: Permissions): Promise<v | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | @@ -314,7 +314,7 @@ startUsingPermission(tokenID: number, permissionName: Permissions, callback: Asy | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | @@ -369,7 +369,7 @@ stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<vo | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is not used with | @@ -417,7 +417,7 @@ stopUsingPermission(tokenID: number, permissionName: Permissions, callback: Asyn | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100002 | The specified tokenID does not exist or it does not refer to an application process. | | 12100003 | The specified permission does not exist or it is not an user_grant permission. | | 12100004 | The interface is not used with | @@ -445,7 +445,7 @@ try { ## privacyManager.on -on(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void +on(type: 'activeStateChange', permissionList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void 订阅指定权限列表的权限使用状态变更事件。 @@ -458,7 +458,7 @@ on(type: 'activeStateChange', permissionNameList: Array<Permissions>, call | 参数名 | 类型 | 必填 | 说明 | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'activeStateChange',权限使用状态变更事件。 | -| permissionNameList | Array<Permissions> | 是 | 订阅的权限名列表,为空时表示订阅所有的权限使用状态变化。 | +| permissionList | Array<Permissions> | 是 | 订阅的权限名列表,为空时表示订阅所有的权限使用状态变化。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 是 | 订阅指定权限使用状态变更事件的回调。 | **错误码:** @@ -467,7 +467,7 @@ on(type: 'activeStateChange', permissionNameList: Array<Permissions>, call | 错误码ID | 错误信息 | | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100001 | The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256. | | 12100004 | The interface is called repeatedly with the same input. | | 12100005 | The registration time has exceeded the limitation. | | 12100007 | Service is abnormal. | @@ -478,9 +478,9 @@ on(type: 'activeStateChange', permissionNameList: Array<Permissions>, call ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList = []; +let permissionList = []; try { - privacyManager.on('activeStateChange', permissionNameList, (data) => { + privacyManager.on('activeStateChange', permissionList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -490,7 +490,7 @@ try { ## privacyManager.off -off(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void; +off(type: 'activeStateChange', permissionList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void; 取消订阅指定权限列表的权限使用状态变更事件。 @@ -503,7 +503,7 @@ off(type: 'activeStateChange', permissionNameList: Array<Permissions>, cal | 参数名 | 类型 | 必填 | 说明 | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'activeStateChange',权限使用状态变更事件。 | -| permissionNameList | Array<Permissions> | 是 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | +| permissionList | Array<Permissions> | 是 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 否 | 取消订阅指定tokenId与指定权限名状态变更事件的回调。| **错误码:** @@ -513,7 +513,7 @@ off(type: 'activeStateChange', permissionNameList: Array<Permissions>, cal | 错误码ID | 错误信息 | | -------- | -------- | | 12100001 | The parameter is invalid. The permissionName in list is all invalid or the list size is larger than 1024. | -| 12100004 | The interface is not used with | +| 12100004 | The interface is not used together with "on"| | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | @@ -522,9 +522,9 @@ off(type: 'activeStateChange', permissionNameList: Array<Permissions>, cal ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList = []; +let permissionList = []; try { - privacyManager.off('activeStateChange', permissionNameList); + privacyManager.off('activeStateChange', permissionList); }catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-process.md b/zh-cn/application-dev/reference/apis/js-apis-process.md index 8f9f63a038ed0a31cd4e02b0985db02181b7e553..eb8f6cf090140a3e536e19a519488db43ff668df 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-process.md +++ b/zh-cn/application-dev/reference/apis/js-apis-process.md @@ -18,13 +18,8 @@ import process from '@ohos.process'; | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| egid | number | 是 | 否 | 进程的有效组标识。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。| -| euid | number | 是 | 否 | 进程的有效用户身份。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | -| gid | number | 是 | 否 | 进程的组标识。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。| | uid | number | 是 | 否 | 进程的用户标识。 | -| groups | number[] | 是 | 否 | 带有补充组id的数组。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | | pid | number | 是 | 否 | 当前进程的pid。 | -| ppid | number | 是 | 否 | 当前进程的父进程的pid。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | | tid8+ | number | 是 | 否 | 当前线程的tid。 | @@ -120,50 +115,6 @@ let result = process.getPastCpuTime() ; ``` -## process.runCmd - -runCmd(command: string, options?: { timeout?: number, killSignal?: number | string, maxBuffer?: number }): ChildProcess - -通过runcmd可以fork一个新的进程来运行一段shell,并返回ChildProcess对象。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| command | string | 是 | shell命令。 | -| options | Object | 否 | 相关选项参数。 | - -**表1** options - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| timeout | number | 否 | 子进程运行的毫秒数,当子进程运行时间超出此时间,则父进程发送killSignal信号给子进程。timeout默认为0。 | -| killSignal | number \| string | 否 | 子进程运行时间超出timeout时,父进程发送killSignal 信号给子进程。killSignal 默认为'SIGTERM'。 | -| maxBuffer | number | 否 | 子进程标准输入输出的最大缓冲区大小,当超出此大小时则终止子进程。maxBuffer默认1024\*1024。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| [ChildProcess](#childprocess) | 子进程对象。 | - -**示例:** - -```js -let child = process.runCmd('ls', { maxBuffer : 2 }); -let result = child.wait(); -child.getOutput.then(val=>{ - console.log("child.getOutput = " + val); -}) -``` - - ## process.abort abort(): void @@ -179,118 +130,6 @@ process.abort(); ``` -## process.on - -on(type: string, listener: EventListener): void - -存储用户所触发的事件。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| type | string | 是 | 存储事件的type。 | -| listener | [EventListener](#eventlistener) | 是 | 回调的事件。 | - -**示例:** - -```js -process.on("data", (e)=>{ - console.log("data callback"); -}) -``` - - -## process.off - -off(type: string): boolean - -删除用户存储的事件。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| type | string | 是 | 删除事件的type。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| boolean | 事件删除成功则返回true,没有成功则为false。| - -**示例:** - -```js -process.on("data", (e)=>{ - console.log("data callback"); -}) -let result = process.off("data"); -``` - - -## process.cwd - -cwd(): string - -获取进程的工作目录。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| string| 返回当前进程的工作目录。 | - -**示例:** - -```js -let path = process.cwd(); -``` - - -## process.chdir - -chdir(dir: string): void - -更改进程的当前工作目录。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| dir | string | 是 | 路径。 | - -**示例:** - -```js -process.chdir('/system'); -``` - - ## process.uptime uptime(): number @@ -728,157 +567,4 @@ kill(signal: number, pid: number): boolean let pro = new process.ProcessManager(); let pres = process.pid; let result = pro.kill(28, pres); -``` - - -## ChildProcess - -ChildProcess对象为创建的新的子进程,主进程可以获取子进程的标准输入输出,以及发送信号和关闭子进程,可以通过[process.runCmd](#processruncmd)获取ChildProcess对象。 - -**系统接口:** 此接口为系统接口。 - -### 属性 - -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.Utils.Lang - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| pid | number | 是 | 否 | 子进程的pid。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | -| ppid | number | 是 | 否 | 子进程的父进程的pid。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | -| exitCode | number | 是 | 否 | 子进程的退出码。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。| -| killed | boolean | 是 | 否 | 父进程给子进程发信号是否成功。
**系统接口:** 此接口为系统接口。
此接口仅用于对应用的测试。 | - - -### wait - -wait(): Promise<number> - -等待子进程运行结束,返回promise对象,其值为子进程的退出码。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 异步返回子进程的退出码。 | - -**示例:** - -```js -let child = process.runCmd('ls'); -let result = child.wait(); -result.then(val=>{ - console.log("result = " + val); -}) -``` - - -### getOutput - -getOutput(): Promise<Uint8Array> - -获取子进程的标准输出。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Promise<Uint8Array> | 异步返回标准输出的字节流。 | - -**示例:** - -```js -let child = process.runCmd('ls'); -let result = child.wait(); -child.getOutput().then(val=>{ - console.log("child.getOutput = " + val); -}) -``` - - -### getErrorOutput - -getErrorOutput(): Promise<Uint8Array> - -获取子进程的标准错误输出。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Promise<Uint8Array> | 异步返回标准错误输出的字节流。 | - -**示例:** - -```js -let child = process.runCmd('madir test.text'); -let result = child.wait(); -child.getErrorOutput().then(val=>{ - console.log("child.getErrorOutput= " + val); -}) -``` - - -### close - -close(): void - -关闭正在运行的子进程。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**示例:** - -```js -let child = process.runCmd('sleep 5; ls'); -child.close(); -``` - - -### kill - -kill(signal: number | string): void - -用于发送信号给子进程,结束指定进程。 - -**系统接口:** 此接口为系统接口。 - -此接口仅用于对应用的测试。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| signal | number \| string | 是 | 数字或字符串。 | - -**示例:** - -```js -let child = process.runCmd('sleep 5; ls'); -child.kill(9); -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-prompt.md b/zh-cn/application-dev/reference/apis/js-apis-prompt.md index ea3d513f6271e4d8f426ea22e83035b45e62527c..a41981e8e95b1459b63fce66d94482809b3e7280 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-prompt.md +++ b/zh-cn/application-dev/reference/apis/js-apis-prompt.md @@ -44,11 +44,11 @@ prompt.showToast({ **系统能力:** SystemCapability.ArkUI.ArkUI.Full。 -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 显示的文本信息。 | -| duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | -| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置,无上限值,默认单位vp。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| message | string | 是 | 显示的文本信息。 | +| duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | +| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置,无上限值,默认单位vp。 | ## prompt.showDialog @@ -145,11 +145,11 @@ prompt.showDialog({ **系统能力:** SystemCapability.ArkUI.ArkUI.Full -| 名称 | 类型 | 必填 | 说明 | -| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 标题文本。 | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 内容文本。 | -| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | 否 | 对话框中按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 | +| 名称 | 类型 | 必填 | 说明 | +| ------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| title | string | 否 | 标题文本。 | +| message | string | 否 | 内容文本。 | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | 否 | 对话框中按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 | ## ShowDialogSuccessResponse @@ -256,7 +256,7 @@ prompt.showActionMenu({ | 名称 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 标题文本。 | +| title | string | 否 | 标题文本。 | | buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | 是 | 菜单中菜单项按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-6个按钮。大于6个按钮时弹窗不显示。 | ## ActionMenuSuccessResponse @@ -275,8 +275,8 @@ prompt.showActionMenu({ **系统能力:** SystemCapability.ArkUI.ArkUI.Full -| 名称 | 类型 | 必填 | 说明 | -| ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 按钮文本内容。 | -| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 按钮文本颜色。 | +| 名称 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | -------------- | +| text | string | 是 | 按钮文本内容。 | +| color | string | 是 | 按钮文本颜色。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-radio.md b/zh-cn/application-dev/reference/apis/js-apis-radio.md index e4b9820b11024bba97664856f3fa020da0af66a2..6c62e6118b310315f335d472f3ccae9c4467ec0d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-radio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-radio.md @@ -10,7 +10,7 @@ ## 导入模块 ``` -import radio from '@ohos.telephony.radio' +import radio from '@ohos.telephony.radio'; ``` ## radio.getRadioTech @@ -45,7 +45,7 @@ getRadioTech\(slotId: number, callback: AsyncCallback<\{psRadioTech: RadioTechno ```js let slotId = 0; -radio.getRadioTech(slotId, (err, data) =>{ +radio.getRadioTech(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -127,7 +127,7 @@ getNetworkState\(callback: AsyncCallback\): void **示例:** ```js -radio.getNetworkState((err, data) =>{ +radio.getNetworkState((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -831,7 +831,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback): void 设置主卡所在卡槽的索引号。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -872,7 +872,7 @@ setPrimarySlotId\(slotId: number\): Promise\ 设置主卡所在卡槽的索引号。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -920,7 +920,7 @@ getIMEI(callback: AsyncCallback): void 获取设备的指定卡槽的IMEI。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -958,7 +958,7 @@ getIMEI(slotId: number, callback: AsyncCallback): void 获取设备的指定卡槽的IMEI。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -998,7 +998,7 @@ getIMEI(slotId?: number): Promise 获取设备的指定卡槽的IMEI。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1045,7 +1045,7 @@ getMEID(callback: AsyncCallback): void 获取设备的指定卡槽的MEID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1083,7 +1083,7 @@ getMEID(slotId: number, callback: AsyncCallback): void 获取设备的指定卡槽的MEID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1123,7 +1123,7 @@ getMEID(slotId?: number): Promise 获取设备的指定卡槽的MEID。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1170,7 +1170,7 @@ getUniqueDeviceId(callback: AsyncCallback): void 获取设备的指定卡槽的唯一设备ID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1208,7 +1208,7 @@ getUniqueDeviceId(slotId: number, callback: AsyncCallback): void 获取设备的指定卡槽的唯一设备ID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1248,7 +1248,7 @@ getUniqueDeviceId(slotId?: number): Promise 获取设备的指定卡槽的唯一设备ID。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1295,7 +1295,7 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback\): void 发送更新小区位置请求。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION @@ -1332,7 +1332,7 @@ sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): 发送更新小区位置请求。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION @@ -1371,7 +1371,7 @@ sendUpdateCellLocationRequest\(slotId?: number): Promise 发送更新小区位置请求。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION @@ -1418,7 +1418,7 @@ getCellInformation(callback: AsyncCallback>): void 获取小区信息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION @@ -1456,7 +1456,7 @@ getCellInformation(slotId: number, callback: AsyncCallback\> 获取小区信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION @@ -1543,7 +1543,7 @@ setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCa 设置网络选择模式。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1593,7 +1593,7 @@ setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise 设置网络选择模式。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1651,7 +1651,7 @@ getNetworkSearchInformation\(slotId: number, callback: AsyncCallback 获取网络搜索信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1735,7 +1735,7 @@ getNrOptionMode(callback: AsyncCallback): void 获取Nr选项模式 。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.CoreService @@ -1770,7 +1770,7 @@ getNrOptionMode(slotId: number, callback: AsyncCallback): void 获取Nr选项模式 。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.CoreService @@ -1807,7 +1807,7 @@ getNrOptionMode(slotId?: number): Promise 获取Nr选项模式 。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.CoreService @@ -1851,7 +1851,7 @@ turnOnRadio(callback: AsyncCallback): void 打开Radio。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1889,7 +1889,7 @@ turnOnRadio(slotId: number, callback: AsyncCallback): void 打开Radio。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1929,7 +1929,7 @@ turnOnRadio(slotId?: number): Promise 打开Radio。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1976,7 +1976,7 @@ turnOffRadio(callback: AsyncCallback): void 关闭Radio。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2014,7 +2014,7 @@ turnOffRadio(slotId: number, callback: AsyncCallback): void 关闭Radio。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2054,7 +2054,7 @@ turnOffRadio(slotId?: number): Promise 关闭Radio。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2101,7 +2101,7 @@ setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback 设置首选网络。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2140,7 +2140,7 @@ setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise< 设置首选网络。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2187,7 +2187,7 @@ getPreferredNetwork\(slotId: number, callback: AsyncCallback 获取首选网络。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2271,7 +2271,7 @@ getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback 获取特定IMS服务类型的IMS注册状态信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2357,7 +2357,7 @@ on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: 订阅imsRegStateChange事件,使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2397,7 +2397,7 @@ off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback 取消订阅imsRegStateChange事件,使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2435,7 +2435,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 无线接入技术。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ------------------------- | ---- | ------------------------------------------------------------ | @@ -2458,7 +2458,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络信号强度信息对象。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------------- | --------------------------- | ---- | ------------------ | @@ -2470,7 +2470,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------- | ---- | ------------------------------------------------------------ | @@ -2486,7 +2486,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络注册状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | @@ -2505,7 +2505,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络注册状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------------------- | ---- | -------------------------- | @@ -2519,7 +2519,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 非独立组网状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------------- | ---- | ---------------------------------------------------------- | @@ -2535,7 +2535,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 选网模式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------------------- | ---- | -------------- | @@ -2547,9 +2547,9 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 首选网络模式。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------------------------------------------------- | ---- | --------------------------------------------- | @@ -2592,9 +2592,9 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ----------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | @@ -2608,9 +2608,9 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { CDMA小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ------------ | @@ -2624,9 +2624,9 @@ CDMA小区信息。 GSM小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | -------------------- | @@ -2641,9 +2641,9 @@ GSM小区信息。 LTE小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------------- | ------- | ---- | ----------------------- | @@ -2660,9 +2660,9 @@ LTE小区信息。 NR小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---------------- | @@ -2677,9 +2677,9 @@ NR小区信息。 TD-SCDMA小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------ | @@ -2694,9 +2694,9 @@ TD-SCDMA小区信息。 WCDMA小区信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------ | @@ -2711,9 +2711,9 @@ WCDMA小区信息。 NR的选择模式。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------- | ---- | ---------------------------------- | @@ -2726,9 +2726,9 @@ NR的选择模式。 网络搜索结果。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ---------------------- | ------------------------------------------------- | ---- | -------------- | @@ -2739,9 +2739,9 @@ NR的选择模式。 网络信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------------- | --------------------------------------------------- | ---- | -------------- | @@ -2754,9 +2754,9 @@ NR的选择模式。 网络信息状态。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------- | ---- | ---------------- | @@ -2769,9 +2769,9 @@ NR的选择模式。 网络选择模式选项。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------------------ | --------------------------------------------- | ---- | -------------------------------------- | @@ -2784,9 +2784,9 @@ NR的选择模式。 IMS注册状态。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ---------------- | ---- | -------- | @@ -2797,9 +2797,9 @@ IMS注册状态。 IMS注册技术。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------------- | ---- | --------------- | @@ -2812,9 +2812,9 @@ IMS注册技术。 IMS注册信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ----------- | ---------------------------- | ---- | ------------- | @@ -2825,9 +2825,9 @@ IMS注册信息。 IMS服务类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ---------- | ---- | ---------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index dcf6443aab41e058fb9a23741c3200da1d5e7b4d..f60cfaed73ab60480c0f13be76391cd404214a7c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-request.md +++ b/zh-cn/application-dev/reference/apis/js-apis-request.md @@ -16,24 +16,6 @@ import request from '@ohos.request'; ## 限制与约束 - -在开发FA模型下的应用程序时, 默认支持https,如果要支持http,需要在config.json里增加network标签,属性标识 "cleartextTraffic": true。即: - -```js -var config = { - "deviceConfig": { - "default": { - "network": { - "cleartextTraffic": true - } - //... - } - } -} -``` - -在开发stage模型下的应用程序时,不涉及属性标识 "cleartextTraffic"。 - 下载服务器需要支持HTTP协议的head方法,能够通过Content-length获取下载数据大小,否则下载任务失败,可通过[on('fail')7+](#onfail7)查看失败原因。 上传目前仅支持HTTP请求,不支持HTTPS。 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 a9730a9f75e06f699156c449338d52ebb8c1d855..6a30bba2bd23574989482edb27fbf0c7fd7c870c 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 @@ -2395,6 +2395,142 @@ getNumberByName(resName: string): number } ``` +### getDrawableDescriptor10+ + +getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; + +用户获取指定资源ID对应的DrawableDescriptor对象,使用同步方式返回资源对应的DrawableDescriptor,用于图标的显示。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resId | number | 是 | 资源ID值 | +| [density](#screendensity) | number | 否 | 资源获取需要的屏幕密度,默认为0 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------- | +| DrawableDescriptor | 资源ID值对应的DrawableDescriptor对象 | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**示例:** + ```ts + try { + this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + try { + this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getDrawableDescriptor10+ + +getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; + +用户获取指定resource对应的DrawableDescriptor对象,使用同步方式返回资源对应的DrawableDescriptor,用于图标的显示。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | 是 | 资源信息 | +| [density](#screendensity) | number | 否 | 资源获取需要的屏幕密度,默认为0 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ----------------- | +| DrawableDescriptor | 资源ID值对应的DrawableDescriptor对象 | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**示例:** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.icon').id + }; + try { + this.context.resourceManager.getDrawableDescriptor(resource); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + try { + this.context.resourceManager.getDrawableDescriptor(resource, 120); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getDrawableDescriptorByName10+ + +getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; + +用户获取指定资源名称对应的DrawableDescriptor对象,使用同步方式返回资源对应的DrawableDescriptor,用于图标的显示。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ---- | +| resName | string | 是 | 资源名称 | +| [density](#screendensity) | number | 否 | 资源获取需要的屏幕密度,默认为0 | + +**返回值:** + +| 类型 | 说明 | +| ------ | --------- | +| DrawableDescriptor | 资源ID值对应的DrawableDescriptor对象 | + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**示例:** + ```ts + try { + this.context.resourceManager.getDrawableDescriptorByName('icon'); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + try { + this.context.resourceManager.getDrawableDescriptorByName('icon', 120); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getString(deprecated) diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index be9f645ab42c723e38cbb7e8f38876424841afe9..4afbde5bb95dc7df32b41f8d62c9cb42b800e960 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -233,7 +233,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | 参数名 | 类型 | 必填 | 说明 | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | bgMode | [BackgroundMode](#backgroundmode) | 是 | 向系统申请的后台模式。 | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击后跳转的界面。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | @@ -311,7 +311,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | 参数名 | 类型 | 必填 | 说明 | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | bgMode | [BackgroundMode](#backgroundmode) | 是 | 向系统申请的后台模式。 | | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。 | @@ -388,7 +388,7 @@ stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): vo | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | **错误码**: @@ -444,7 +444,7 @@ stopBackgroundRunning(context: Context): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| context | Context | 是 | 应用运行的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | **返回值**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index ee84849081ba394ad675f8591072bd5acde14c25..2e445a19cedb7885d4abde49f38054c2e4d4225b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -346,6 +346,7 @@ isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean | 9700001 | Memory operation failed. | | 9700002 | Parcel operation failed. | | 9700003 | System service operation failed. | +| 9700004 | Checking workInfo failed. | **示例**: @@ -391,6 +392,7 @@ isLastWorkTimeOut(workId: number): Promise\ | 9700001 | Memory operation failed. | | 9700002 | Parcel operation failed. | | 9700003 | System service operation failed. | +| 9700004 | Checking workInfo failed. | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index 307b3bd73a7b84c49a2f8cb3f19a2cb9b6829d2e..fde185a857f3003328e25b39b80d3838061c6fd2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -362,7 +362,7 @@ replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback< | 错误码ID | 错误信息 | | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 200002 | if the uri is not exist. | **示例:** @@ -573,7 +573,7 @@ router.getParams(); | 名称 | 说明 | | -------- | ------------------------------------------------------------ | -| Standard | 标准模式。
目标页面会被添加到页面路由栈顶,无论栈中是否存在相同url的页面。
**说明:**不使用路由跳转模式时,按标准模式跳转。 | +| Standard | 标准模式。
目标页面会被添加到页面路由栈顶,无论栈中是否存在相同url的页面。
**说明:** 不使用路由跳转模式时,按标准模式跳转。 | | Single | 单实例模式。
如果目标页面的url在页面栈中已经存在同url页面,离栈顶最近的页面会被移动到栈顶,移动后的页面为新建页。
如目标页面的url在页面栈中不存在同url页面,按标准模式跳转。 | ## 完整示例 @@ -597,7 +597,7 @@ export default { // 在detail页面中 export default { onInit() { - console.info('showData1:' + router.getParams()[data1]); + console.info('showData1:' + router.getParams()['data1']); } } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-rpc.md b/zh-cn/application-dev/reference/apis/js-apis-rpc.md index 4a3af98149c6aef5924d47cb4c0ed1e3285b2086..edf7e7169821b9950ddd0f7cd28cd2e6df300c16 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-rpc.md +++ b/zh-cn/application-dev/reference/apis/js-apis-rpc.md @@ -5649,7 +5649,7 @@ asObject(): IRemoteObject return this; } } - let remoteObject = new TestAbility().asObject(); + let remoteObject = new TestAbility("testObject").asObject(); ``` **示例:** @@ -6058,7 +6058,7 @@ isObjectDead(): boolean **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | --------------------- | ----------------------- | --------------------------------- | | PING_TRANSACTION | 1599098439 (0x5f504e47) | 内部指令码,用于测试IPC服务正常。 | | DUMP_TRANSACTION | 1598311760 (0x5f444d50) | 内部指令码,获取Binder内部状态。 | @@ -6974,7 +6974,7 @@ isObjectDead(): boolean **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 - | 名称 | 默认值 | 说明 | + | 名称 | 值 | 说明 | | ------------- | ---- | ----------------------------------------------------------- | | TF_SYNC | 0 | 同步调用标识。 | | TF_ASYNC | 1 | 异步调用标识。 | @@ -8259,13 +8259,13 @@ getDescriptor(): string } } let testRemoteObject = new TestRemoteObject("testObject"); + console.log("RpcServer: descriptor is: " + descriptor); try { let descriptor = testRemoteObject.getDescriptor(); } catch(error) { console.info("rpc get local interface fail, errorCode " + error.code); console.info("rpc get local interface fail, errorMessage " + error.message); } - console.log("RpcServer: descriptor is: " + descriptor); ``` ### getInterfaceDescriptor(deprecated) @@ -8340,8 +8340,8 @@ modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void try { this.modifyLocalInterface(this, descriptor); } catch(error) { - console.info(rpc attach local interface fail, errorCode " + error.code); - console.info(rpc attach local interface fail, errorMessage " + error.message); + console.info(" rpc attach local interface fail, errorCode " + error.code); + console.info(" rpc attach local interface fail, errorMessage " + error.message); } } registerDeathRecipient(recipient: MyDeathRecipient, flags: number) { @@ -8414,7 +8414,7 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void 映射内存保护类型: - | 名称 | 默认值 | 说明 | + | 名称 | 值 | 说明 | | ---------- | --- | ------------------ | | PROT_EXEC | 4 | 映射的内存可执行 | | PROT_NONE | 0 | 映射的内存不可访问 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md index 5bbab366210ab5c920f97732f24d33e47f037468..6782838ee05b97cda45cfe5066a4b43259adb1e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @@ -12,12 +12,14 @@ import screenlock from '@ohos.screenLock'; ``` -## EventType +## EventType9+ 定义系统事件类型。 **系统能力:** SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 + | 事件类型 | 说明 | | ------------------ | ------------------------ | | beginWakeUp | 表示设备开始唤醒。 | @@ -35,15 +37,17 @@ import screenlock from '@ohos.screenLock'; | screenlockEnabled | 表示锁屏是否启用。 | | serviceRestart | 表示锁屏服务进行重启。 | -## SystemEvent +## SystemEvent9+ 定义系统事件回调参数结构。 **系统能力:** SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 + | 名称 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ------------- | -| eventType | [EventType](#eventtype) | 是 | 系统事件类型。 | +| eventType | [EventType](#eventtype9) | 是 | 系统事件类型。 | | params | string | 是 | 系统事件参数。 | ## screenlock.isLocked9+ @@ -54,6 +58,8 @@ isLocked(): boolean **系统能力:** SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 + **返回值:** | 类型 | 说明 | @@ -66,26 +72,6 @@ isLocked(): boolean let isLocked = screenlock.isLocked(); ``` -## screenlock.isSecure9+ - -isSecure(): boolean - -判断当前设备的屏幕锁定是否安全(安全屏幕锁定意味着解锁屏幕需要密码、图案或其他用户身份识别)。 - -**系统能力:** SystemCapability.MiscServices.ScreenLock - -**返回值:** - -| 类型 | 说明 | -| ------- | ------------------------------------------------------------ | -| boolean | 返回true表示当前设备的屏幕锁定安全;返回false表示当前设备的屏幕锁定不安全。 | - -**示例:** - -```js -let isSecure = screenlock.isSecure(); -``` - ## screenlock.unlock9+ unlock(callback: AsyncCallback<boolean>): void @@ -94,6 +80,8 @@ unlock(callback: AsyncCallback<boolean>): void **系统能力:** SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -128,6 +116,8 @@ unlock(): Promise<boolean> **系统能力:** SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 + **返回值:** | 类型 | 说明 | @@ -236,7 +226,7 @@ onSystemEvent(callback: Callback<SystemEvent>): boolean | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------------- | -| callback | Callback\<[SystemEvent](#systemevent)> | 是 | 锁屏相关的系统事件回调函数。 | +| callback | Callback\<[SystemEvent](#systemevent9)> | 是 | 锁屏相关的系统事件回调函数。 | **返回值:** @@ -266,7 +256,7 @@ try { ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: string, parameter: number, callback: AsyncCallback<boolean>): void +sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback<boolean>): void 应用发送事件到锁屏服务。使用callback异步回调。 @@ -278,7 +268,7 @@ sendScreenLockEvent(event: string, parameter: number, callback: AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------ | ---- | -------------------- | -| event | string | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "lockScreenResult",表示锁屏结果。
- "screenDrawDone",表示屏幕绘制完成。 | +| event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "lockScreenResult",表示锁屏结果。
- "screenDrawDone",表示屏幕绘制完成。 | | parameter | number | 是 | 事件结果。
- parameter为0,表示成功。例如解锁成功或锁屏成功。
- parameter为1,表示失败。例如解锁失败或锁屏失败。
- parameter为2,表示取消。例如锁屏取消或解锁取消。 | | callback | AsyncCallback\ | 是 | 回调函数。返回true表示发送事件成功;返回false表示发送事件失败。 | @@ -304,7 +294,7 @@ screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: string, parameter: number): Promise<boolean> +sendScreenLockEvent(event: String, parameter: number): Promise<boolean> 应用发送事件到锁屏服务。使用Promise异步回调。 @@ -316,7 +306,7 @@ sendScreenLockEvent(event: string, parameter: number): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | --------------------------------------- | -| event | string | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "lockScreenResult",表示锁屏结果。
- "screenDrawDone",表示屏幕绘制完成。 | +| event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "lockScreenResult",表示锁屏结果。
- "screenDrawDone",表示屏幕绘制完成。 | | parameter | number | 是 | 事件结果。
- parameter为0,表示成功。例如解锁成功或锁屏成功。
- parameter为1,表示失败。例如解锁失败或锁屏失败。
- parameter为2,表示取消。例如锁屏取消或解锁取消。 | **返回值:** @@ -343,7 +333,7 @@ isScreenLocked(callback: AsyncCallback<boolean>): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock @@ -373,7 +363,7 @@ isScreenLocked(): Promise<boolean> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock @@ -401,7 +391,7 @@ isSecureMode(callback: AsyncCallback<boolean>): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock @@ -431,7 +421,7 @@ isSecureMode(): Promise<boolean> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock @@ -458,7 +448,7 @@ unlockScreen(callback: AsyncCallback<void>): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock @@ -488,7 +478,7 @@ unlockScreen(): Promise<void> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 +> 从API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.MiscServices.ScreenLock 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 282bab54a75a6fb77c5fe7a8ac5e1457b319b4bf..c7fb672f2ba72e3bd74f40b4816241fd4a127118 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -2661,7 +2661,7 @@ try { ## sensor.getAngleVariation9+ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, - callback: AsyncCallback): void + callback: AsyncCallback<Array<number>>): void 计算两个旋转矩阵之间的角度变化。 @@ -2717,7 +2717,7 @@ try { ## sensor.getAngleVariation9+ -getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise +getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> 得到两个旋转矩阵之间的角度变化。 @@ -2777,7 +2777,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void +getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void 根据旋转矢量获取旋转矩阵。 @@ -2819,7 +2819,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(rotationVector: Array<number>): Promise +getRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> 根据旋转矢量获取旋转矩阵。 @@ -2866,7 +2866,7 @@ try { ## sensor.transformRotationMatrix9+ transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, - callback: AsyncCallback): void + callback: AsyncCallback<Array<number>>): void 根据指定坐标系映射旋转矩阵。 @@ -2913,7 +2913,7 @@ try { ## sensor.transformRotationMatrix9+ -transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> 根据指定坐标系映射旋转矩阵。 @@ -2964,7 +2964,7 @@ try { ## sensor.getQuaternion9+ -getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void +getQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void 根据旋转向量计算归一化四元数。 @@ -3006,7 +3006,7 @@ try { ## sensor.getQuaternion9+ -getQuaternion(rotationVector: Array<number>): Promise +getQuaternion(rotationVector: Array<number>): Promise<Array<number>> 根据旋转向量计算归一化四元数。 @@ -3052,7 +3052,7 @@ try { ## sensor.getOrientation9+ -getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void +getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void 根据旋转矩阵计算设备方向。 @@ -3101,7 +3101,7 @@ try { ## sensor.getOrientation9+ -getOrientation(rotationMatrix: Array<number>): Promise +getOrientation(rotationMatrix: Array<number>): Promise<Array<number>> 根据旋转矩阵计算设备的方向。 @@ -3193,7 +3193,7 @@ try { ## sensor.getRotationMatrix9+ -getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>): Promise<RotationMatrixResponse> 根据重力矢量和地磁矢量计算旋转矩阵。 @@ -3239,7 +3239,7 @@ try { ## sensor.getSensorList9+ -getSensorList(callback: AsyncCallback): void +getSensorList(callback: AsyncCallback<Array<Sensor>>): void 获取设备上的所有传感器信息。 @@ -3249,7 +3249,7 @@ getSensorList(callback: AsyncCallback): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | 是 | 回调函数,返回传感器属性列表。 | +| callback | AsyncCallback<Array<[Sensor](#sensor9)>> | 是 | 回调函数,返回传感器属性列表。 | **错误码**: @@ -3279,7 +3279,7 @@ try { ## sensor.getSensorList9+ - getSensorList(): Promise< Array<Sensor>> + getSensorList(): Promise<Array<Sensor>> 获取设备上的所有传感器信息。 @@ -3289,7 +3289,7 @@ try { | 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------- | -| promise | Promise | 是 | Promise对象,返回传感器属性列表。 | +| promise | Promise<Array<[Sensor](#sensor9)>> | 是 | Promise对象,返回传感器属性列表。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-sim.md b/zh-cn/application-dev/reference/apis/js-apis-sim.md index 2b2def039972e6044e70c0b7afed2fae469204a5..b6fd5d7be0c995263715fc242412c1398845055d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sim.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sim.md @@ -665,7 +665,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback): voi 获取SIM卡账户信息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -706,7 +706,7 @@ getSimAccountInfo(slotId: number): Promise 获取SIM卡账户信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -754,7 +754,7 @@ getActiveSimAccountInfoList(callback: AsyncCallback>): vo 获取活跃SIM卡账户信息列表。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -793,7 +793,7 @@ getActiveSimAccountInfoList(): Promise>; 获取活跃SIM卡账户信息列表。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -834,7 +834,7 @@ setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback): void 设置默认语音业务的卡槽ID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -875,7 +875,7 @@ setDefaultVoiceSlotId(slotId: number): Promise\ 设置默认语音业务的卡槽ID。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -923,7 +923,7 @@ setShowName\(slotId: number, name: string, callback: AsyncCallback\): voi 设置指定卡槽SIM卡显示的名称。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -964,7 +964,7 @@ setShowName\(slotId: number, name: string\): Promise\ 设置指定卡槽SIM卡显示的名称。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1013,7 +1013,7 @@ getShowName(slotId: number, callback: AsyncCallback): void 获取指定卡槽SIM卡的名称。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1053,7 +1053,7 @@ getShowName(slotId: number): Promise 获取指定卡槽SIM卡的名称。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1100,7 +1100,7 @@ setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): 设置指定卡槽SIM卡的号码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1142,7 +1142,7 @@ setShowNumber\(slotId: number, number: string\): Promise\ 设置指定卡槽SIM卡的号码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1191,7 +1191,7 @@ getShowNumber(slotId: number, callback: AsyncCallback): void 获取指定卡槽SIM卡的号码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1231,7 +1231,7 @@ getShowNumber(slotId: number): Promise 获取指定卡槽SIM卡的号码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1278,7 +1278,7 @@ activateSim(slotId: number, callback: AsyncCallback): void 激活指定卡槽SIM卡。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1318,7 +1318,7 @@ activateSim(slotId: number): Promise\ 激活指定卡槽SIM卡。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1365,7 +1365,7 @@ deactivateSim(slotId: number, callback: AsyncCallback): void 禁用指定卡槽SIM卡。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1405,7 +1405,7 @@ deactivateSim(slotId: number): Promise\ 禁用指定卡槽SIM卡。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1452,7 +1452,7 @@ setLockState(slotId: number, options: LockInfo, callback: AsyncCallback 设置指定卡槽SIM卡的锁状态。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1553,7 +1553,7 @@ getLockState(slotId: number, lockType: LockType, callback: AsyncCallback 获取指定卡槽SIM卡的锁状态。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -1644,7 +1644,7 @@ alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback 更改Pin密码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1687,7 +1687,7 @@ alterPin(slotId: number, newPin: string, oldPin: string): Promise 解锁指定卡槽SIM卡密码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -1923,7 +1923,7 @@ unlockPuk(slotId: number, newPin: string, puk: string, callback: AsyncCallback 解锁指定卡槽SIM卡密码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2113,7 +2113,7 @@ unlockPuk2(slotId: number, newPin2: string, puk2: string, callback: AsyncCallbac 解锁指定卡槽SIM卡密码的解锁密码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2158,7 +2158,7 @@ unlockPuk2(slotId: number, newPin2: string, puk2: string): Promise<LockStatus 解锁指定卡槽SIM卡密码的解锁密码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2230,7 +2230,7 @@ getSimIccId(slotId: number, callback: AsyncCallback): void 获取指定卡槽SIM卡的ICCID。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2270,7 +2270,7 @@ getSimIccId(slotId: number): Promise 获取指定卡槽SIM卡的ICCID。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2317,7 +2317,7 @@ getVoiceMailIdentifier(slotId: number, callback: AsyncCallback): void 获取指定卡槽中SIM卡语音信箱的alpha标识符。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2357,7 +2357,7 @@ getVoiceMailIdentifier(slotId: number): Promise 获取指定卡槽中SIM卡语音信箱的alpha标识符。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2404,7 +2404,7 @@ getVoiceMailNumber(slotId: number, callback: AsyncCallback): void 获取指定卡槽中SIM卡的语音信箱号。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2444,7 +2444,7 @@ getVoiceMailNumber(slotId: number): Promise 获取指定卡槽中SIM卡的语音信箱号。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2492,7 +2492,7 @@ setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: 设置语音邮件信息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2535,7 +2535,7 @@ setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string): Promise< 设置语音邮件信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -2585,7 +2585,7 @@ getSimTelephoneNumber(slotId: number, callback: AsyncCallback): void 获取指定卡槽中SIM卡的MSISDN。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2625,7 +2625,7 @@ getSimTelephoneNumber(slotId: number): Promise 获取指定卡槽中SIM卡的MSISDN。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2672,7 +2672,7 @@ getSimGid1(slotId: number, callback: AsyncCallback): void 获取指定卡槽中SIM卡的组标识符级别1(GID1)。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2712,7 +2712,7 @@ getSimGid1(slotId: number): Promise 获取指定卡槽中SIM卡的组标识符级别1(GID1)。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2759,7 +2759,7 @@ getIMSI(slotId: number, callback: AsyncCallback): void 获取国际移动用户识别码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2799,7 +2799,7 @@ getIMSI(slotId: number): Promise 获取国际移动用户识别码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2846,7 +2846,7 @@ getOperatorConfigs(slotId: number, callback: AsyncCallback> 获取运营商配置。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE @@ -2933,7 +2933,7 @@ queryIccDiallingNumbers(slotId: number, type: ContactType, callback: AsyncCallba 查询SIM卡联系人号码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.READ_CONTACTS @@ -2975,7 +2975,7 @@ queryIccDiallingNumbers(slotId: number, type: ContactType): Promise): vo 发送信封命令。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -3374,7 +3374,7 @@ sendEnvelopeCmd(slotId: number, cmd: string): Promise 发送信封命令。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -3422,7 +3422,7 @@ sendTerminalResponseCmd(slotId: number, cmd: string, callback: AsyncCallback 发送终端响应命令。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -3512,7 +3512,7 @@ unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback\): 设置短信服务中心(SMSC)地址。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限 @@ -293,7 +293,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\ 设置短信服务中心(SMSC)地址。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限 @@ -343,7 +343,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback\): void 获取短信服务中心(SMSC)地址。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限 @@ -383,7 +383,7 @@ getSmscAddr\(slotId: number\): Promise 获取短信服务中心(SMSC)地址。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限 @@ -449,7 +449,7 @@ splitMessage(content: string, callback: AsyncCallback>): void 将长短信拆分为多个片段。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SEND_MESSAGES @@ -489,7 +489,7 @@ splitMessage(content: string): Promise> 将长短信拆分为多个片段。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SEND_MESSAGES @@ -536,7 +536,7 @@ addSimMessage(options: SimMessageOptions, callback: AsyncCallback): void 添加SIM卡消息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -581,7 +581,7 @@ addSimMessage(options: SimMessageOptions): Promise 添加SIM卡消息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -633,7 +633,7 @@ delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback): 删除SIM卡消息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -675,7 +675,7 @@ delSimMessage(slotId: number, msgIndex: number): Promise 删除SIM卡信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -724,7 +724,7 @@ updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback 更新SIM卡消息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -823,7 +823,7 @@ getAllSimMessages(slotId: number, callback: AsyncCallback> 获取所有SIM卡消息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS @@ -910,7 +910,7 @@ setCBConfig(options: CBConfigOptions, callback: AsyncCallback): void 设置小区广播配置。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS @@ -956,7 +956,7 @@ setCBConfig(options: CBConfigOptions): Promise 设置小区广播配置。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.RECEIVE_SMS @@ -1009,7 +1009,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback 获取短信段信息。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1048,7 +1048,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise 获取短信段信息。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1094,7 +1094,7 @@ isImsSmsSupported(slotId: number, callback: AsyncCallback): void 如果IMS已注册并且在IMS上支持SMS,则支持通过IMS发送SMS。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1131,7 +1131,7 @@ isImsSmsSupported(slotId: number): Promise 如果IMS已注册并且在IMS上支持SMS,则支持通过IMS发送SMS。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1175,7 +1175,7 @@ getImsShortMessageFormat(callback: AsyncCallback): void 获取IMS上支持的SMS格式。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1211,7 +1211,7 @@ getImsShortMessageFormat(): Promise 获取IMS上支持的SMS格式。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1249,7 +1249,7 @@ decodeMms(mmsFilePathName: string | Array, callback: AsyncCallback): Promise 彩信解码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1330,7 +1330,7 @@ encodeMms(mms: MmsInformation, callback: AsyncCallback>): void 彩信编码。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1375,7 +1375,7 @@ encodeMms(mms: MmsInformation): Promise> 彩信编码。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力**:SystemCapability.Telephony.SmsMms @@ -1425,7 +1425,7 @@ promise.then(data => { 短信实例。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | @@ -1446,7 +1446,7 @@ promise.then(data => { 短信类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------------- | ---- | ---------------------------------------- | @@ -1461,7 +1461,7 @@ promise.then(data => { 发送短信的参数和回调。根据SendMessageOptions中的可选参数content的值判断短信类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | @@ -1478,7 +1478,7 @@ promise.then(data => { 回调实例。返回短信发送结果、存储已发送短信的URI和是否为长短信的最后一部分。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ------------------------------- | ---- | ----------------------------------------------------------------------------------------- | @@ -1491,7 +1491,7 @@ promise.then(data => { 回调实例,返回短信送达报告。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---- | ------------------- | ---- | -------------- | @@ -1502,7 +1502,7 @@ promise.then(data => { 短信发送结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------------------ | ---- | ------------------------------------------------------ | @@ -1515,9 +1515,9 @@ promise.then(data => { 彩信信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------------ | ---- | ---------- | @@ -1529,9 +1529,9 @@ promise.then(data => { 彩信发送请求。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------------------------------------ | ---- | ------------ | @@ -1555,9 +1555,9 @@ promise.then(data => { 彩信发送配置。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1570,9 +1570,9 @@ promise.then(data => { 彩信通知索引。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------------- | ---------------------------------- | ---- | -------- | @@ -1591,9 +1591,9 @@ promise.then(data => { 彩信确认索引。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1605,9 +1605,9 @@ promise.then(data => { 彩信检索配置。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------- | ------------------------------------ | ---- | -------- | @@ -1630,9 +1630,9 @@ promise.then(data => { 彩信读取原始索引。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------- | ---- | -------- | @@ -1647,9 +1647,9 @@ promise.then(data => { 彩信读取记录索引。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------- | ---- | -------- | @@ -1664,9 +1664,9 @@ promise.then(data => { 彩信附件。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------------------------ | ---- | ------------------ | @@ -1685,9 +1685,9 @@ promise.then(data => { 彩信地址。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------- | ---- | ------ | @@ -1698,9 +1698,9 @@ promise.then(data => { 消息类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------- | ---- | -------------------- | @@ -1718,9 +1718,9 @@ promise.then(data => { 彩信优先级类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------- | ---- | -------------- | @@ -1732,9 +1732,9 @@ promise.then(data => { 彩信版本类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------------- | ---- | ----------- | @@ -1747,9 +1747,9 @@ promise.then(data => { 彩信字符集。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------------- | ------ | ------------------- | @@ -1772,9 +1772,9 @@ promise.then(data => { 处理类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------- | ---- | -------- | @@ -1786,9 +1786,9 @@ promise.then(data => { 报告类型。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------- | ---- | ---- | @@ -1799,9 +1799,9 @@ promise.then(data => { 小区广播配置选项。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------- | -------------------- | ---- | ------------ | @@ -1815,9 +1815,9 @@ promise.then(data => { SIM卡消息状态。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------- | ---- | --------------------------- | @@ -1831,9 +1831,9 @@ SIM卡消息状态。 设备网络制式。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------- | ---- | ---- | @@ -1844,9 +1844,9 @@ SIM卡消息状态。 短信编码方案。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -1859,9 +1859,9 @@ SIM卡消息状态。 SIM卡消息选项。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------ | -------------------------------------- | ---- | -------------- | @@ -1874,9 +1874,9 @@ SIM卡消息选项。 更新SIM卡消息选项。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------- | -------------------------------------- | ---- | -------------- | @@ -1890,9 +1890,9 @@ SIM卡消息选项。 SIM卡短消息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | -------------------------------------- | ---- | ------------- | @@ -1904,9 +1904,9 @@ SIM卡短消息。 彩信发送标识。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------- | ---------------------------------- | ---- | ------ | @@ -1920,9 +1920,9 @@ SIM卡短消息。 彩信回复标志。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1935,9 +1935,9 @@ SIM卡短消息。 短信段信息。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------------- | ---------------------------------------- | ---- | ------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index 944301f6c5509de4702c4535529b73987f310208..7c005e050863732e1af8ea6b4003135aeac1a1fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -1,5 +1,7 @@ # @ohos.net.socket (Socket连接) +本模块提供利用Socket进行数据传输的能力,支持TCPSocket、UDPSocket、WebSocket和TLSSocket。 + > **说明:** > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -12,7 +14,7 @@ import socket from '@ohos.net.socket'; ## socket.constructUDPSocketInstance -constructUDPSocketInstance\(\): UDPSocket +constructUDPSocketInstance(): UDPSocket 创建一个UDPSocket对象。 @@ -38,7 +40,7 @@ UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constr ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void 绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。 @@ -76,7 +78,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。 @@ -118,7 +120,7 @@ promise .then(() => { ### send -send\(options: UDPSendOptions, callback: AsyncCallback\): void +send(options: UDPSendOptions, callback: AsyncCallback\): void 通过UDPSocket连接发送数据。使用callback方式作为异步方法。 @@ -165,7 +167,7 @@ udp.send({ ### send -send\(options: UDPSendOptions\): Promise +send(options: UDPSendOptions): Promise\ 通过UDPSocket连接发送数据。使用Promise方式作为异步方法。 @@ -216,7 +218,7 @@ promise.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 关闭UDPSocket连接。使用callback方式作为异步方法。 @@ -246,7 +248,7 @@ udp.close(err => { ### close -close\(\): Promise +close(): Promise\ 关闭UDPSocket连接。使用Promise方式作为异步方法。 @@ -275,12 +277,12 @@ promise.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void 获取UDPSocket状态。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)方法调用成功后,才可调用此方法。 +>**说明:** +>bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -321,12 +323,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### getState -getState\(\): Promise +getState(): Promise\ 获取UDPSocket状态。使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)方法调用成功后,才可调用此方法。 +>**说明:** +>bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -336,7 +338,7 @@ getState\(\): Promise | 类型 | 说明 | | :----------------------------------------------- | :----------------------------------------- | -| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取UDPSocket状态的结果。 | +| Promise\<[SocketStateBase](#socketstatebase)\> | 以Promise形式返回获取UDPSocket状态的结果。 | **示例:** @@ -360,12 +362,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): void 设置UDPSocket连接的其他属性。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)方法调用成功后,才可调用此方法。 +>**说明:** +>bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -414,12 +416,12 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions\): Promise +setExtraOptions(options: UDPExtraOptions): Promise\ 设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)方法调用成功后,才可调用此方法。 +>**说明:** +>bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -469,9 +471,9 @@ promise.then(() => { ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。 @@ -482,7 +484,7 @@ on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: Sock | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | -| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 | +| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | 是 | 回调函数。 | **示例:** @@ -494,13 +496,13 @@ udp.on('message', value => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -526,9 +528,9 @@ udp.off('message'); ``` -### on\('listening' | 'close'\) +### on('listening' | 'close') -on\(type: 'listening' | 'close', callback: Callback\): void +on(type: 'listening' | 'close', callback: Callback\): void 订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。 @@ -554,13 +556,13 @@ udp.on('close', () => { ``` -### off\('listening' | 'close'\) +### off('listening' | 'close') -off\(type: 'listening' | 'close', callback?: Callback\): void +off(type: 'listening' | 'close', callback?: Callback\): void 取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -593,9 +595,9 @@ udp.off('close'); ``` -### on\('error'\) +### on('error') -on\(type: 'error', callback: ErrorCallback\): void +on(type: 'error', callback: ErrorCallback): void 订阅UDPSocket连接的error事件。使用callback方式作为异步方法。 @@ -618,13 +620,13 @@ udp.on('error', err => { ``` -### off\('error'\) +### off('error') -off\(type: 'error', callback?: ErrorCallback\): void +off(type: 'error', callback?: ErrorCallback): void 取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -654,7 +656,7 @@ udp.off('error'); 目标地址信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | @@ -666,7 +668,7 @@ udp.off('error'); UDPSocket发送参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------- | ---- | -------------- | @@ -677,7 +679,7 @@ UDPSocket发送参数。 UDPSocket连接的其他属性。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------------- | ------- | ---- | -------------------------------- | @@ -691,7 +693,7 @@ UDPSocket连接的其他属性。 Socket的状态信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------- | ------- | ---- | ---------- | @@ -703,7 +705,7 @@ Socket的状态信息。 Socket的连接信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | @@ -720,7 +722,7 @@ UDP 其余错误码映射形式为:2301000 + Linux内核错误码。 ## socket.constructTCPSocketInstance -constructTCPSocketInstance\(\): TCPSocket +constructTCPSocketInstance(): TCPSocket 创建一个TCPSocket对象。 @@ -745,7 +747,7 @@ TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constr ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void 绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。 @@ -783,7 +785,7 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。 @@ -825,10 +827,13 @@ promise.then(() => { ### connect -connect\(options: TCPConnectOptions, callback: AsyncCallback\): void +connect(options: TCPConnectOptions, callback: AsyncCallback\): void 连接到指定的IP地址和端口。使用callback方法作为异步方法。 +>**说明:** +>bind方法调用成功后,才可调用此方法。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -863,7 +868,7 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time ### connect -connect\(options: TCPConnectOptions\): Promise +connect(options: TCPConnectOptions): Promise\ 连接到指定的IP地址和端口。使用promise方法作为异步方法。 @@ -905,12 +910,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions, callback: AsyncCallback\): void +send(options: TCPSendOptions, callback: AsyncCallback\): void 通过TCPSocket连接发送数据。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -954,12 +959,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions\): Promise +send(options: TCPSendOptions): Promise\ 通过TCPSocket连接发送数据。使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1007,7 +1012,7 @@ promise1.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 关闭TCPSocket连接。使用callback方式作为异步方法。 @@ -1043,7 +1048,7 @@ tcp.close(err => { ### close -close\(\): Promise +close(): Promise\ 关闭TCPSocket连接。使用Promise方式作为异步方法。 @@ -1078,12 +1083,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void 获取对端Socket地址。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1123,12 +1128,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(\): Promise +getRemoteAddress(): Promise\ 获取对端Socket地址。使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1167,12 +1172,12 @@ promise1.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void 获取TCPSocket状态。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1212,12 +1217,12 @@ promise.then(() => { ### getState -getState\(\): Promise +getState(): Promise\ 获取TCPSocket状态。使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1256,12 +1261,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void 设置TCPSocket连接的其他属性。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1312,12 +1317,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ 设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** ->[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。 +>**说明:** +>bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1370,9 +1375,9 @@ promise.then(() => { ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。 @@ -1395,13 +1400,13 @@ tcp.on('message', value => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void +off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1427,9 +1432,9 @@ tcp.off('message'); ``` -### on\('connect' | 'close'\) +### on('connect' | 'close') -on\(type: 'connect' | 'close', callback: Callback\): void +on(type: 'connect' | 'close', callback: Callback\): void 订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。 @@ -1455,13 +1460,13 @@ tcp.on('close', data => { ``` -### off\('connect' | 'close'\) +### off('connect' | 'close') -off\(type: 'connect' | 'close', callback?: Callback\): void +off(type: 'connect' | 'close', callback?: Callback\): void 取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1494,9 +1499,9 @@ tcp.off('close'); ``` -### on\('error'\) +### on('error') -on\(type: 'error', callback: ErrorCallback\): void +on(type: 'error', callback: ErrorCallback): void 订阅TCPSocket连接的error事件。使用callback方式作为异步方法。 @@ -1519,13 +1524,13 @@ tcp.on('error', err => { ``` -### off\('error'\) +### off('error') -off\(type: 'error', callback?: ErrorCallback\): void +off(type: 'error', callback?: ErrorCallback): void 取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1555,7 +1560,7 @@ tcp.off('error'); TCPSocket连接的参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------- | ---- | -------------------------- | @@ -1566,7 +1571,7 @@ TCPSocket连接的参数。 TCPSocket发送请求的参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | @@ -1577,7 +1582,7 @@ TCPSocket发送请求的参数。 TCPSocket连接的其他属性。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------------- | ------- | ---- | ------------------------------------------------------------ | @@ -1622,7 +1627,7 @@ TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constr ### bind9+ -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void 绑定IP地址和端口。使用callback方法作为异步方法。 @@ -1660,7 +1665,7 @@ tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind9+ -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 绑定IP地址和端口。使用Promise方法作为异步方法。 @@ -1702,7 +1707,7 @@ promise.then(() => { ### getState9+ -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void 在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。 @@ -1742,7 +1747,7 @@ tls.getState((err, data) => { ### getState9+ -getState\(\): Promise +getState(): Promise\ 在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。 @@ -1781,7 +1786,7 @@ promise.then(() => { ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void 在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。 @@ -1833,7 +1838,7 @@ tls.setExtraOptions({ ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ 在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。 @@ -1888,7 +1893,7 @@ promise.then(() => { ### connect9+ -connect(options: TLSConnectOptions, callback: AsyncCallback\): void +connect(options: TLSConnectOptions, callback: AsyncCallback\): void 在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。 @@ -1982,7 +1987,7 @@ tlsOneWay.connect(oneWayOptions, (err, data) => { ### connect9+ -connect(options: TLSConnectOptions): Promise\ +connect(options: TLSConnectOptions): Promise\ 在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。 @@ -1998,7 +2003,7 @@ connect(options: TLSConnectOptions): Promise\ | 类型 | 说明 | | ------------------------------------------- | ----------------------------- | -| Promise\ | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。| +| Promise\ | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。| **错误码:** @@ -2083,7 +2088,7 @@ tlsOneWay.connect(oneWayOptions).then(data => { ### getRemoteAddress9+ -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void 在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。 @@ -2093,7 +2098,7 @@ getRemoteAddress\(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 | +| callback | AsyncCallback\<[NetAddress](#netaddress)\> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 | **错误码:** @@ -2116,7 +2121,7 @@ tls.getRemoteAddress((err, data) => { ### getRemoteAddress9+ -getRemoteAddress\(\): Promise\ +getRemoteAddress(): Promise\ 在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。 @@ -2148,7 +2153,7 @@ promise.then(() => { ### getCertificate9+ -getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void +getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。 @@ -2158,7 +2163,7 @@ getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。| +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。| **错误码:** @@ -2182,7 +2187,7 @@ tls.getCertificate((err, data) => { ### getCertificate9+ -getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> +getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。 @@ -2192,7 +2197,7 @@ getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> | 类型 | 说明 | | -------------- | -------------------- | -| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 | +| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 | **错误码:** @@ -2214,7 +2219,7 @@ tls.getCertificate().then(data => { ### getRemoteCertificate9+ -getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void +getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。 @@ -2224,7 +2229,7 @@ getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 | +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 | **错误码:** @@ -2247,7 +2252,7 @@ tls.getRemoteCertificate((err, data) => { ### getRemoteCertificate9+ -getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> +getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。 @@ -2257,7 +2262,7 @@ getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> | 类型 | 说明 | | -------------- | -------------------- | -| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 | +| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 | **错误码:** @@ -2278,7 +2283,7 @@ tls.getRemoteCertificate().then(data => { ### getProtocol9+ -getProtocol(callback: AsyncCallback\): void +getProtocol(callback: AsyncCallback\): void 在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。 @@ -2288,7 +2293,7 @@ getProtocol(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\ | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。| +| callback | AsyncCallback\ | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。| **错误码:** @@ -2312,7 +2317,7 @@ tls.getProtocol((err, data) => { ### getProtocol9+ -getProtocol():Promise\ +getProtocol():Promise\ 在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。 @@ -2322,7 +2327,7 @@ getProtocol():Promise\ | 类型 | 说明 | | -------------- | -------------------- | -| Promise\ | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 | +| Promise\ | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 | **错误码:** @@ -2344,7 +2349,7 @@ tls.getProtocol().then(data => { ### getCipherSuite9+ -getCipherSuite(callback: AsyncCallback\>): void +getCipherSuite(callback: AsyncCallback\\>): void 在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。 @@ -2354,7 +2359,7 @@ getCipherSuite(callback: AsyncCallback\>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 | +| callback | AsyncCallback\\> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 | **错误码:** @@ -2379,7 +2384,7 @@ tls.getCipherSuite((err, data) => { ### getCipherSuite9+ -getCipherSuite(): Promise\> +getCipherSuite(): Promise\\> 在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。 @@ -2389,7 +2394,7 @@ getCipherSuite(): Promise\> | 类型 | 说明 | | ---------------------- | --------------------- | -| Promise\> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 | +| Promise\\> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 | **错误码:** @@ -2412,7 +2417,7 @@ tls.getCipherSuite().then(data => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(callback: AsyncCallback\>): void +getSignatureAlgorithms(callback: AsyncCallback\\>): void 在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。 @@ -2422,7 +2427,7 @@ getSignatureAlgorithms(callback: AsyncCallback\>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | 是 | 回调函数,返回双方支持的签名算法。 | +| callback | AsyncCallback\\> | 是 | 回调函数,返回双方支持的签名算法。 | **错误码:** @@ -2445,7 +2450,7 @@ tls.getSignatureAlgorithms((err, data) => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(): Promise\> +getSignatureAlgorithms(): Promise\\> 在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。 @@ -2455,7 +2460,7 @@ getSignatureAlgorithms(): Promise\> | 类型 | 说明 | | ---------------------- | -------------------- | -| Promise\> | 以Promise形式返回获取到的双方支持的签名算法。 | +| Promise\\> | 以Promise形式返回获取到的双方支持的签名算法。 | **错误码:** @@ -2476,7 +2481,7 @@ tls.getSignatureAlgorithms().then(data => { ### send9+ -send(data: string, callback: AsyncCallback\): void +send(data: string, callback: AsyncCallback\): void 在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。 @@ -2487,7 +2492,7 @@ send(data: string, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -----------------------------| ---- | ---------------| | data | string | 是 | 发送的数据内容。 | -| callback | AsyncCallback\ | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | **错误码:** @@ -2514,7 +2519,7 @@ tls.send("xxxx", (err) => { ### send9+ -send(data: string): Promise\ +send(data: string): Promise\ 在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。 @@ -2541,7 +2546,7 @@ send(data: string): Promise\ | 类型 | 说明 | | -------------- | -------------------- | -| Promise\ | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | +| Promise\ | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | **示例:** @@ -2555,7 +2560,7 @@ tls.send("xxxx").then(() =>{ ### close9+ -close(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。 @@ -2565,7 +2570,7 @@ close(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -----------------------------| ---- | ---------------| -| callback | AsyncCallback\ | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 | +| callback | AsyncCallback\ | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 | **错误码:** @@ -2590,7 +2595,7 @@ tls.close((err) => { ### close9+ -close(): Promise\ +close(): Promise\ 在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。 @@ -2600,7 +2605,7 @@ close(): Promise\ | 类型 | 说明 | | -------------- | -------------------- | -| Promise\ | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 | +| Promise\ | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 | **错误码:** @@ -2631,7 +2636,7 @@ TLS连接的操作。 | -------------- | ------------------------------------- | --- |-------------- | | address | [NetAddress](#netaddress) | 是 | 网关地址。 | | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。| -| ALPNProtocols | Array\ | 否 | ALPN协议。 | +| ALPNProtocols | Array\ | 否 | ALPN协议。 | ## TLSSecureOptions9+ @@ -2641,11 +2646,11 @@ TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参 | 名称 | 类型 | 必填 | 说明 | | --------------------- | ------------------------------------------------------ | --- |----------------------------------- | -| ca | string \| Array\ | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。| +| ca | string \| Array\ | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。| | cert | string | 否 | 本地客户端的数字证书。 | | key | string | 否 | 本地数字证书的私钥。 | | password | string | 否 | 读取私钥的密码。 | -| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 | +| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | 否 | TLS的协议版本。 | | useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 | | signatureAlgorithms | string | 否 | 通信过程中的签名算法。 | | cipherSuite | string | 否 | 通信过程中的加密套件。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-stationary.md b/zh-cn/application-dev/reference/apis/js-apis-stationary.md index acb4c1767efade3f622be4c76d074bc653319e17..e4c3ad1ac1ca278f18abda61c3b2b9d41d881c84 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stationary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stationary.md @@ -18,11 +18,11 @@ import stationary from '@ohos.stationary' 服务响应抽象接口。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | state | [ActivityState](#activitystate) | 是 | 否 | 设备状态变化返回值。 | @@ -30,9 +30,9 @@ import stationary from '@ohos.stationary' 设备状态类型。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary -| 名称 | 描述 | +| 名称 | 说明 | | -------- | -------- | | still | 绝对静止。 | | relativeStill | 相对静止。 | @@ -41,9 +41,9 @@ import stationary from '@ohos.stationary' 设备状态事件。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary -| 变量 | 值 | 说明 | +| 名称 | 值 | 说明 | | ------------------------------ | ---- | ---------------------------------------- | | ENTER | 1 | 进入。 | | EXIT | 2 | 退出。 | @@ -53,9 +53,9 @@ import stationary from '@ohos.stationary' 设备状态返回值。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary -| 变量 | 值 | 说明 | +| 名称 | 值 | 说明 | | ------------------------------ | ---- | ---------------------------------------- | | ENTER | 1 | 进入。 | | EXIT | 2 | 退出。 | @@ -66,11 +66,11 @@ on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callba 设备状态管理,订阅设备状态服务。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary **参数:** -| 名称 | 类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | activity | [ActivityType](#activitytype) | 是 | 设备状态能力类型。 | | event | [ActivityEvent](#activityevent) | 是 | 事件类型。 | @@ -92,11 +92,11 @@ once(activity: ActivityType, callback: Callback<ActivityResponse>): void 设备状态管理,查询设备状态。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary **参数:** -| 名称 | 类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | activity | [ActivityType](#activitytype) | 是 | 设备状态能力类型。 | | callback | Callback<[ActivityResponse](#activityresponse)\> | 是 | 回调函数,接收上报状态变化事件。 | @@ -115,11 +115,11 @@ off(activity: ActivityType, event: ActivityEvent, callback?: Callback<Activit 设备状态管理,取消订阅设备状态服务。 -**系统能力** SystemCapability.Msdp.DeviceStatus.Stationary +**系统能力**:SystemCapability.Msdp.DeviceStatus.Stationary **参数:** -| 名称 | 类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | activity | [ActivityType](#activitytype) | 是 | 设备状态能力类型。 | | event | [ActivityEvent](#activityevent) | 是 | 事件类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-app.md b/zh-cn/application-dev/reference/apis/js-apis-system-app.md index 8a03bfb8c5842b16ec77570d4a577400b3073893..2595d85b30288d01f32894c7d4d70fe9f740c32d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-app.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-app.md @@ -199,7 +199,7 @@ export default { ## ScreenOnVisible(deprecated) -screenOnVisible(options?: ScreenOnVisibleOptions) +screenOnVisible(options?: ScreenOnVisibleOptions): void 定义屏幕唤醒时是否保持应用可见。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-battery.md b/zh-cn/application-dev/reference/apis/js-apis-system-battery.md index f56300b43ae741066b0f693c16eb652fa02dbb62..a93d7a157b3d30225be59b1f287a96a6d7c07874 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-battery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-battery.md @@ -25,7 +25,7 @@ getStatus(options?: GetStatusOptions): void; **参数:** -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | options | [GetStatusOptions](#getstatusoptions) | 否 | 包含接口调用结果的对象。 | @@ -46,7 +46,9 @@ battery.getStatus({ 包含接口调用结果的对象。 -| 参数名 | 类型 | 必填 | 说明 | +**系统能力:** SystemCapability.PowerManager.BatteryManager.Core + +| 名称 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | | success | (data: [BatteryResponse](#batteryresponse)) => void | 否 | 接口调用成功的回调函数,data为[BatteryResponse](#batteryresponse)类型的返回值。 | | fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | @@ -56,7 +58,9 @@ battery.getStatus({ 包含充电状态及剩余电量的对象。 -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| charging | boolean | 当前电池是否在充电中。 | -| level | number | 当前电池的电量,取值范围:0.00 - 1.00 。 | +**系统能力:** SystemCapability.PowerManager.BatteryManager.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| charging | boolean | 是 | 否 | 当前电池是否在充电中。 | +| level | number | 是 | 否 | 当前电池的电量,取值范围:0.00 - 1.00 。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md b/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md index 7e4043be8c4c7b55404274d2c931e897324eeefb..3efeff8a95fd8528d3fdd5aed4836ebce8caa29c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -19,14 +19,12 @@ import bluetooth from '@system.bluetooth'; 开始搜寻附近的低功耗蓝牙外围设备。此操作比较耗费系统资源,请在搜索并连接到设备后调用[bluetooth.stopBLEScan](#bluetoothstopblescanobject)方法停止搜索。 -**需要权限:** ohos.permission.DISCOVER_BLUETOOTH、ohos.permission.LOCATION - **系统能力:** SystemCapability.Communication.Bluetooth.Lite **参数:** **表1** StartBLEScanOptions -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | interval | number | 否 | 上报设备的间隔,单位毫秒,默认值为0。0表示找到新设备立即上报,其他数值根据传入的间隔上报。 | | success | Function | 否 | 接口调用成功的回调函数。 | @@ -42,7 +40,7 @@ import bluetooth from '@system.bluetooth'; console.log('call bluetooth.startBLEScan success.'); }, fail(code, data) { - console.log('call bluetooth.startBLEScan failed, code: ${code}, data: ${data}.'); + console.log('call bluetooth.startBLEScan failed, code:' + code + ', data:' + data); }, complete() { console.log('call bluetooth.startBLEScan complete.'); @@ -55,14 +53,12 @@ import bluetooth from '@system.bluetooth'; 停止搜寻附近的低功耗蓝牙外围设备。与[bluetooth.startBLEScan(OBJECT)](#bluetoothstartblescanobject)接口配套使用。 -**需要权限:** ohos.permission.DISCOVER_BLUETOOTH、ohos.permission.LOCATION - **系统能力:** SystemCapability.Communication.Bluetooth.Lite **参数:** **表2** StopBLEScanOptions -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | success | Function | 否 | 接口调用成功的回调函数。 | | fail | Function | 否 | 接口调用失败的回调函数。 | @@ -76,7 +72,7 @@ import bluetooth from '@system.bluetooth'; console.log('call bluetooth.stopBLEScan success.'); }, fail(data, code) { - console.log('call bluethooth.stopBLEScan fail, code: ${code}, data: ${data}.'); + console.log('call bluethooth.stopBLEScan fail, code:' + code + ', data:' + data); }, complete() { console.log('call bluethooth.stopBLEScan complete.'); @@ -89,14 +85,12 @@ import bluetooth from '@system.bluetooth'; 订阅寻找到新设备。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。 -**需要权限:** ohos.permission.DISCOVER_BLUETOOTH、ohos.permission.LOCATION - **系统能力:** SystemCapability.Communication.Bluetooth.Lite **参数:** **表3** SubscribeBLEFoundOptions -| 参数 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | success | Function | 是 | 寻找到新设备上报时调用的回调函数。 | | fail | Function | 否 | 接口调用失败的回调函数。 | @@ -125,7 +119,7 @@ import bluetooth from '@system.bluetooth'; console.log('call bluetooth.subscribeBLEFound success, data: ${data}.'); }, fail(data, code) { - console.log('call bluetooth.startBLEScan failed, data: ${data}, code: ${code}.'); + console.log('call bluetooth.startBLEScan failed, code:' + code + ', data:' + data); } }); ``` @@ -135,8 +129,6 @@ import bluetooth from '@system.bluetooth'; 解除订阅寻找到新设备。 -**需要权限:** ohos.permission.DISCOVER_BLUETOOTH、ohos.permission.LOCATION - **系统能力:** SystemCapability.Communication.Bluetooth.Lite **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md b/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md index 2f019ad51b018cbde409f27d59c69b904f123aa9..32723c518063df016497a1f104d2bf0baf056442 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @@ -45,7 +45,7 @@ getValue(options?: GetBrightnessOptions): void ## brightness.setValue -etValue(options?: SetBrightnessOptions): void +setValue(options?: SetBrightnessOptions): void 设置设备当前的屏幕亮度值。 @@ -74,7 +74,7 @@ etValue(options?: SetBrightnessOptions): void ## brightness.getMode -getMode(options?: GetBrightnessModeOptions: void +getMode(options?: GetBrightnessModeOptions): void 获得当前屏幕亮度模式。 @@ -161,6 +161,8 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void 获取屏幕亮度的参数对象。 +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + | 名称 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | success | (data: [BrightnessResponse](#brightnessresponse)) => void | 否 | 接口调用成功的回调函数。data为[BrightnessResponse](#brightnessresponse)类型的返回值。 | @@ -171,6 +173,8 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void 设置屏幕亮度的参数对象。 +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + | 名称 | 类型 | 必填 | 说明 | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | value | number | 是 | 屏幕亮度,值为1-255之间的整数。
- 如果值小于等于0,系统按1处理。
- 如果值大于255,系统按255处理。
- 如果值为小数,系统将处理为整数。例如设置为8.1,系统按8处理。 | @@ -182,14 +186,18 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void 包含屏幕亮度的对象。 -| 名称 | 类型 | 说明 | -| -------- | -------- | -------- | -| value | number | 屏幕亮度,范围:1到255。 | +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| value | number | 是 | 否 | 屏幕亮度,范围:1到255。 | ## GetBrightnessModeOptions 获取屏幕亮度模式的参数对象。 +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + | 名称 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | 否 | 接口调用成功的回调函数。data为[BrightnessModeResponse](#brightnessmoderesponse)类型的返回值。 | @@ -200,6 +208,8 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void 设置屏幕亮度模式的参数对象。 +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + | 名称 | 类型 | 必填 | 说明 | | -------- | ------------------------------------ | ---- | ------------------------------------------------------ | | mode | number | 是 | 0表示手动调节屏幕亮度模式,1表示自动调节屏幕亮度模式。 | @@ -211,14 +221,18 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void 包含屏幕亮度模式的对象。 -| 名称 | 类型 | 说明 | -| -------- | -------- | -------- | -| mode | number | 0表示手动调节屏幕亮度模式,1表示自动调节屏幕亮度模式。 | +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| mode | number | 是 | 否 | 0表示手动调节屏幕亮度模式,1表示自动调节屏幕亮度模式。 | ## SetKeepScreenOnOptions 设置屏幕常亮的参数对象。 +**系统能力:** SystemCapability.PowerManager.DisplayPowerManager + | 名称 | 类型 | 必填 | 说明 | | ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | | keepScreenOn | boolean | 是 | true表示保持屏幕常亮,false表示取消屏幕常亮。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-capability.md b/zh-cn/application-dev/reference/apis/js-apis-system-capability.md index e0fdd2062e6a4faa1314218be2c47882e90da0ea..0acb7d8db08f10bc6cc45300ab5839f862839bb8 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-system-capability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-capability.md @@ -16,7 +16,7 @@ import systemcapability from '@ohos.systemCapability' ## systemcapability.querySystemCapabilities -querySystemCapabilities(callback: AsyncCallback): void; +querySystemCapabilities(callback: AsyncCallback<string>): void; 获取系统能力集合的字符串,并调用回调函数。 @@ -51,7 +51,7 @@ querySystemCapabilities(): Promise<string> 获取系统能力的集合。 -**系统能力:** SystemCapability.Startup.SystemInfo +**系统能力:** SystemCapability.Developtools.Syscap **返回值:** @@ -76,6 +76,7 @@ try { > **说明:** -> - 以上接口所返回的system capability集合形式均为编码后的数字字符串形式。 +> +> 以上接口所返回的system capability集合形式均为编码后的数字字符串形式。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md b/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md index 766b981ad11d3891b1b7e366f6c0c9c4cdd1157e..b87349eb95221cd68f45e90b7665ceef1e7d3a49 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @@ -3,7 +3,8 @@ > **说明:** > > 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - +> +> 从API version 9开始废弃, 建议使用[@ohos.security.cryptoFramework的Cipher](js-apis-cryptoFramework.md#Cipher)替代。 ## 导入模块 @@ -18,9 +19,10 @@ import cipher from '@system.cipher'; **系统能力**:SystemCapability.Security.Cipher -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------ | -| text | string | 是 | 返回的内容。 | +| 名称 | 类型 | 可读 | 可写 |说明 | +| ------ | ------ | ---- | ---- | ------------ | +| text | string | 是 | 否 | 返回的内容。 | + ## CipherRsaOptions @@ -28,7 +30,7 @@ import cipher from '@system.cipher'; **系统能力**:SystemCapability.Security.Cipher -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | action | string | 是 | 加密类型,可选项有:
1. encrypt 加密
2. decrypt 解密 | | text | string | 是 | 待加密或解密的文本内容。待加密的文本内容应该是一段普通文本,长度不能超过 keySize / 8 - 66,其中 keySize 是密钥的长度(例如密钥长度为 1024 时,text 不能超过 62 个字节)。待解密的文本内容应该是经过 base64 编码的一段二进制值。base64 编码使用默认风格。 | @@ -44,7 +46,7 @@ import cipher from '@system.cipher'; **系统能力**:SystemCapability.Security.Cipher -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | action | string | 是 | 加密类型,可选项有:
1. encrypt 加密
2. decrypt 解密 | | text | string | 是 | 待加密或解密的文本内容。待加密的文本内容应该是一段普通文本。待解密的文本内容应该是经过 base64 编码的一段二进制值。base64 编码使用默认风格。 | @@ -74,39 +76,39 @@ RSA 算法加解密。 **示例:** ```js -export default { - rsa() { - cipher.rsa({ - //加密 - action: 'encrypt', - //待加密的文本内容 - text: 'hello', - //base64编码后的加密公钥 - key: - 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' + - '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' + +export default { + rsa() { + cipher.rsa({ + //加密 + action: 'encrypt', + //待加密的文本内容 + text: 'hello', + //base64编码后的加密公钥 + key: + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' + + '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' + '+Enz0RzmVFh/4yk6lmqRzuEFQqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBw\n' + - 'jBpApTJ3TeneOo6Z5QIDAQAB', - success: function(data) { - console.log(`handling success:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); + 'jBpApTJ3TeneOo6Z5QIDAQAB', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); - cipher.rsa({ - //解密: - action: 'decrypt', - //待解密的内容,是base64编码后的一段二进制值,解密后是文本内容“hello” - text: + }); + cipher.rsa({ + //解密: + action: 'decrypt', + //待解密的内容,是base64编码后的一段二进制值,解密后是文本内容“hello” + text: 'EPeCFPib6ayKbA0M6oSywARvFZ8dFYfjQv3nY8ikZGtS9UHq2sLPvAfpeIzggSiCxqbWeCftP1XQ\n' + 'Sa+jEpzFlT1qoSTunBbrYzugPTajIJDTg6R1IRsF/J+mmakn0POVPvi4jCo9wqavB324Bx0Wipnc\n' + - 'EU5WO0oBHo5l4x6dTpU=', - //base64编码后的解密私钥 - key: + 'EU5WO0oBHo5l4x6dTpU=', + //base64编码后的解密私钥 + key: 'MIICXgIBAAKBgQCx414QSP3RsYWYzf9mkBMiBAXo6S7Lpva1fKlcuVxjoFC1iMnz\n' + 'D4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ+Enz0RzmVFh/4yk6lmqRzuEF\n' + 'QqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBwjBpApTJ3TeneOo6Z5QIDAQAB\n' + @@ -118,18 +120,18 @@ export default { 'PKoljdXmJeS6rGgzGibstuHLrP3tcIho4+0CQD3ZFWzF/xq0jxKlrpWhnJuNCRfE\n' + 'oO6e9yNvVA8J/5oEDSOcmqSNIp4+RhbUx8InUxnCG6Ryv5aSFu71pYcKrPkCQQCL\n' + 'RUGcm3ZGTnslduB0knNF+V2ndwzDUQ7P74UXT+PjurTPhujFYiuxCEd6ORVnEOzG\n' + - 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + + 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + '8GfqIdUNf+aCG5TZK/kXBF1sqcsi7jXMAf4jBlejVbSVZg==', - success: function(data) { - console.log(`handling success:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); - } - }); + } + }); } } ``` @@ -152,48 +154,48 @@ AES 算法加解密。 **示例:** ```js -export default { - aes() { - cipher.aes({ - //加密 - action: 'encrypt', - //待加密的文本内容 - text: 'hello', - //base64编码后的密钥 - key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', - transformation: 'AES/CBC/PKCS5Padding', - ivOffset: '0', - ivLen: '16', - success: function(data) { - console.log(`handling success:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); +export default { + aes() { + cipher.aes({ + //加密 + action: 'encrypt', + //待加密的文本内容 + text: 'hello', + //base64编码后的密钥 + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); - cipher.aes({ - //解密: - action: 'decrypt', - //待解密的内容,是base64编码后的一段二进制值 - text: '1o0kf2HXwLxHkSh5W5NhzA==', - //base64编码后的密钥 - key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', - transformation: 'AES/CBC/PKCS5Padding', - ivOffset: '0', - ivLen: '16', - success: function(data) { - console.log(`handling success:${data.text}`); - }, - fail: function(data, code) { - console.log(`### cipher.aes encrypt fail ### ${code}:${data}`); + }); + cipher.aes({ + //解密: + action: 'decrypt', + //待解密的内容,是base64编码后的一段二进制值 + text: '1o0kf2HXwLxHkSh5W5NhzA==', + //base64编码后的密钥 + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`handling success:${data.text}`); + }, + fail: function(data, code) { + console.log(`### cipher.aes encrypt fail ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); } - }); + }); } } 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 4215cce99d6414f55b0a047139273a5c87a573a3..6398c8500455323fe8437f4800b402cacf064800 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 @@ -16,7 +16,7 @@ import device from '@system.device'; ## device.getInfo -getInfo(Object): void +getInfo(options?: GetDeviceOptions): void 获取当前设备的信息。 @@ -29,13 +29,27 @@ getInfo(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| success | Function | 否 | 接口调用成功的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | -| complete | Function | 否 | 接口调用结束的回调函数。 | +| options | [GetDeviceOptions](#getdeviceoptions) | 否 | 定义设备信息获取的参数选项。 | -success返回值: +## GetDeviceOptions -| 参数名 | 类型 | 说明 | +定义设备信息获取的参数选项。 + +**系统能力: ** SystemCapability.Startup.SystemInfo + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| success | (data:DeviceResponse)=> void | 否 | 接口调用成功的回调函数。 data为成功返回的设备信息,具体参考[DeviceResponse]。| +| fail | (data:any,code:number)=> void | 否 | 接口调用失败的回调函数。 code为失败返回的错误码。
code:200,表示返回结果中存在无法获得的信息。| +| complete | ()=> void | 否 | 接口调用结束的回调函数。 | + +## DeviceResponse + +设备信息。 + +##系统能力:** SystemCapability.Startup.SystemInfo + +| 名称 | 类型 | 说明 | | -------- | -------- | -------- | | brand | string | 品牌。 | | manufacturer | string | 生产商。 | @@ -51,11 +65,6 @@ success返回值: | releaseType4+ | string | 版本发布类型,值为类型+版本号,如Beta1。
类型可能值有:
- Canary:同一apiVersion下,canary版本之间保持API兼容,beta版本不对canary版本兼容。
- Beta:同一apiVersion下,beta版本之间保持API兼容,release版本不对beta版本兼容。
- Release:release版本会保持5个API版本兼容。 | | deviceType4+ | string | 设备类型。 | -fail返回错误代码: - -| 错误码 | 说明 | -| -------- | -------- | -| 200 | 返回结果中存在无法获得的信息。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-fetch.md b/zh-cn/application-dev/reference/apis/js-apis-system-fetch.md index ed8c646e3d6082c779bd9e02b726cc4c634dbac0..b4e7eb8eccbab3614d8182eb6492a9a9ce189d48 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-fetch.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @@ -14,7 +14,7 @@ import fetch from '@system.fetch'; ``` -## fetch.fetch +## fetch.fetch3+ fetch(Object): void @@ -45,7 +45,7 @@ fetch(Object): void ## FetchResponse -| 参数名 | 类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | code | number | 是 | 否 | 表示服务器的状态code。 | | data | string \| Object | 是 | 否 | 返回数据类型由responseType确定,详见表 responseType与success中data关系。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-location.md b/zh-cn/application-dev/reference/apis/js-apis-system-location.md index 433fb412161875ec2d95864421874b2da19259f0..a9509c8e5b49b608fee4583f4cec72474837304f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-location.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-location.md @@ -21,44 +21,22 @@ ohos.permission.LOCATION ## geolocation.getLocation(deprecated) -getLocation(Object): void +getLocation(options?: GetLocationOption): void 获取设备的地理位置。 > **说明:**
> 从API version 9开始废弃,建议使用[geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation)替代。 +**需要权限**:ohos.permission.LOCATION + **系统能力:** SystemCapability.Location.Location.Lite **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| timeout | number | 否 | 超时时间,单位为ms,默认值为30000。
设置超时,是为了防止出现权限被系统拒绝、定位信号弱或者定位设置不当,导致请求阻塞的情况。超时后会使用fail回调函数。
取值范围为32位正整数。如果设置值小于等于0,系统按默认值处理。 | -| coordType | string | 否 | 坐标系的类型,可通过getSupportedCoordTypes获取可选值,缺省值为wgs84。 | -| success | Function | 否 | 接口调用成功的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | -| complete | Function | 否 | 接口调用结束的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| longitude | number | 设备位置信息:经度。 | -| latitude | number | 设备位置信息:纬度。 | -| altitude | number | 设备位置信息:海拔。 | -| accuracy | number | 设备位置信息:精确度。 | -| time | number | 设备位置信息:时间。 | - -fail返回错误代码: - -| 错误码 | 说明 | -| -------- | -------- | -| 601 | 获取定位权限失败,失败原因:用户拒绝。 | -| 602 | 权限未声明。 | -| 800 | 超时,失败原因:网络状况不佳或GNSS不可用。 | -| 801 | 系统位置开关未打开。 | -| 802 | 该次调用结果未返回前接口又被重新调用,该次调用失败返回错误码。 | +| options | [GetLocationOption](#getlocationoptiondeprecated) | 否 | 单次定位请求的配置参数。 | **示例:** @@ -80,7 +58,7 @@ export default { ## geolocation.getLocationType(deprecated) -getLocationType(Object): void +getLocationType(options?: GetLocationTypeOption): void 获取当前设备支持的定位类型。 @@ -93,15 +71,7 @@ getLocationType(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| success | Function | 否 | 接口调用成功的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | -| complete | Function | 否 | 接口调用结束的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| types | Array<string> | 可选的定位类型['gps', 'network']。 | +| options | [GetLocationTypeOption](#getlocationtypeoptiondeprecated) | 否 | 回调函数,用于接收查询结果,或者接收查询失败的结果。 | **示例:** @@ -123,40 +93,22 @@ export default { ## geolocation.subscribe(deprecated) -subscribe(Object): void +subscribe(options: SubscribeLocationOption): void 订阅设备的地理位置信息。多次调用的话,只有最后一次的调用生效。 > **说明:**
> 从API version 9开始废弃,建议使用[geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange)替代。 +**需要权限**:ohos.permission.LOCATION + **系统能力:** SystemCapability.Location.Location.Lite **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| coordType | string | 否 | 坐标系的类型,可通过getSupportedCoordTypes获取可选值,默认值为wgs84。 | -| success | Function | 是 | 位置信息发生变化的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| longitude | number | 设备位置信息:经度。 | -| latitude | number | 设备位置信息:纬度。 | -| altitude | number | 设备位置信息:海拔。 | -| accuracy | number | 设备位置信息:精确度。 | -| time | number | 设备位置信息:时间。 | - -fail返回错误代码: - -| 错误码 | 说明 | -| -------- | -------- | -| 601 | 获取定位权限失败,失败原因:用户拒绝。 | -| 602 | 权限未声明。 | -| 801 | 系统位置开关未打开。 | +| options | [SubscribeLocationOption](#subscribelocationoptiondeprecated) | 是 | 持续定位的配置参数。 | **示例:** @@ -185,6 +137,8 @@ unsubscribe(): void > **说明:**
> 从API version 9开始废弃,建议使用[geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange)替代。 +**需要权限**:ohos.permission.LOCATION + **系统能力:** SystemCapability.Location.Location.Lite **示例:** @@ -223,4 +177,103 @@ export default { var types = geolocation.getSupportedCoordTypes(); }, } -``` \ No newline at end of file +``` + +## GetLocationOption(deprecated) + +单次定位请求的配置参数。 + +> **说明:**
+> 从API version 9开始废弃,建议使用[geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#CurrentLocationRequest)替代。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Lite + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| timeout | number | 否 | 超时时间,单位为ms,默认值为30000。
设置超时,是为了防止出现权限被系统拒绝、定位信号弱或者定位设置不当,导致请求阻塞的情况。超时后会使用fail回调函数。
取值范围为32位正整数。如果设置值小于等于0,系统按默认值处理。 | +| coordType | string | 否 | 坐标系的类型,可通过getSupportedCoordTypes获取可选值,缺省值为wgs84。 | +| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | 否 | 接口调用成功的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | + +fail返回错误代码: + +| 错误码 | 说明 | +| -------- | -------- | +| 601 | 获取定位权限失败,失败原因:用户拒绝。 | +| 602 | 权限未声明。 | +| 800 | 超时,失败原因:网络状况不佳或GNSS不可用。 | +| 801 | 系统位置开关未打开。 | +| 802 | 该次调用结果未返回前接口又被重新调用,该次调用失败返回错误码。 | + +## GeolocationResponse(deprecated) + +位置信息,包含经度、纬度、定位精度等信息。 + +> **说明:**
+> 从API version 9开始废弃,建议使用[geoLocationManager.Location](js-apis-geoLocationManager.md#location)替代。 + +**系统能力**:SystemCapability.Location.Location.Lite + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| longitude | number | 是 | 否 | 设备位置信息:经度。 | +| latitude | number | 是 | 否 | 设备位置信息:纬度。 | +| altitude | number | 是 | 否 | 设备位置信息:海拔。 | +| accuracy | number | 是 | 否 | 设备位置信息:精确度。 | +| time | number | 是 | 否 | 设备位置信息:时间。 | + +## GetLocationTypeOption(deprecated) + +查询定位类型接口的入参,用于存放回调函数,在查询成功或者失败时接收查询结果。 + +> **说明:**
+> 从API version 9开始废弃。 + +**系统能力**:SystemCapability.Location.Location.Lite + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| success | (data: [GetLocationTypeResponse](#getlocationtyperesponsedeprecated)) => void | 否 | 接口调用成功的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | + +## GetLocationTypeResponse(deprecated) + +当前设备支持的定位类型列表 + +> **说明:**
+> 从API version 9开始废弃。 + +**系统能力**:SystemCapability.Location.Location.Lite + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| types | Array<string> | 是 | 否 | 可选的定位类型['gps', 'network']。 | + +## SubscribeLocationOption(deprecated) + +持续定位请求的配置参数。 + +> **说明:**
+> 从API version 9开始废弃,建议使用[geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#locationrequest)替代。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Lite + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| coordType | string | 否 | 坐标系的类型,可通过getSupportedCoordTypes获取可选值,默认值为wgs84。 | +| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | 是 | 位置信息发生变化的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | + +fail返回错误代码: + +| 错误码 | 说明 | +| -------- | -------- | +| 601 | 获取定位权限失败,失败原因:用户拒绝。 | +| 602 | 权限未声明。 | +| 801 | 系统位置开关未打开。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-network.md b/zh-cn/application-dev/reference/apis/js-apis-system-network.md index dafd8dfb0cc77456536366353b7b3a3a01e9851b..85e7aa74af1e2d315ba9d602d61528d2a1a4caa6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-network.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-network.md @@ -124,7 +124,7 @@ export default { **系统能力:** SystemCapability.Communication.NetManager.Core -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | metered | boolean | 否 |是否按照流量计费。 | | type | string | 是|网络类型,可能的值有2g,3g,4g,5g,wifi,none等。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-notification.md b/zh-cn/application-dev/reference/apis/js-apis-system-notification.md index 90e659026163849de506824f05de742aa919db44..62de17e20deea8e360dd120e81514740aec84907 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-notification.md @@ -17,22 +17,22 @@ import notification from '@system.notification'; **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -| 名称 | 类型 | 可读 | 可写 | 必填 | 描述 | -| ----------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | -| bundleName | string | 是 | 是 | 是 | 单击通知后要重定向到的应用程序的Bundle名。 | -| abilityName | string | 是 | 是 | 是 | 单击通知后要重定向到的应用程序的Ability名称。 | -| uri | string | 是 | 是 | 否 | 要重定向到的页面的uri。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | ---------------------------------------------- | ---- | ------------------------- | +| bundleName | string | 是 | 单击通知后要重定向到的应用程序的Bundle名。 | +| abilityName | string | 是 | 单击通知后要重定向到的应用程序的Ability名称。 | +| uri | string | 否 | 要重定向到的页面的uri。 | ## ShowNotificationOptions **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -| 名称 | 类型 | 可读 | 可写 | 必填 | 描述 | -| ------------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | -| contentTitle | string | 是 | 是 | 否 | 通知标题。 | -| contentText | string | 是 | 是 | 否 | 通知内容。 | -| clickAction | ActionResult | 是 | 是 | 否 | 通知被点击后触发的行为。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ---------------------------------------------- | ---- | ------------------------- | +| contentTitle | string | 否 | 通知标题。 | +| contentText | string | 否 | 通知内容。 | +| clickAction | ActionResult | 否 | 通知被点击后触发的行为。 | ## notification.show diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-package.md b/zh-cn/application-dev/reference/apis/js-apis-system-package.md index aaaae2ffa6001a2ae226d2b333498b789c79522c..252cee0e700766d5591ccf8dbdb5c9d8a5cf251d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-package.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-package.md @@ -23,8 +23,6 @@ hasInstalled(options: CheckPackageHasInstalledOptions): void 查询指定应用是否存在,或者原生应用是否安装。 -**需要权限:** None - **系统能力:** SystemCapability.BundleManager.BundleFramework **参数:** @@ -65,7 +63,7 @@ export default { **系统能力:** SystemCapability.BundleManager.BundleFramework。 -| 参数名 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | |result | boolean | 是 | 指示应用是否已安装。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md b/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md index d7a6269fca2d55fce28433cb4bf7a35a8a8d917d..f43838efc108328c8c10fe6737bd6f352fea1235 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @@ -5,7 +5,7 @@ [系统参数](../../../device-dev/subsystems/subsys-boot-init-sysparam.md)。 > **说明:** -> - 本模块接口从API version 9开始不再维护,建议使用新接口[`@ohos.systemParameterV9`](js-apis-system-parameterV9.md)替代。 +> - 本模块接口从API version 9开始不再维护,建议使用新接口[`@ohos.systemParameterEnhance`](js-apis-system-parameterEnhance.md)替代。 > - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块接口为系统接口。 > - 由于系统参数都是各个系统服务的内部信息和控制参数,每个系统参数都有各自不同的DAC和MAC访问控制权限,三方应用不能使用此类接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md index 3ad1ecd1983a0849dca0c47b44303ae31b62c7da..2f3d54255a9a81a80a337a8877df9e76c032fecc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @@ -1,7 +1,5 @@ # @system.sensor (传感器) -## 模块说明 - sensor模块提供订阅传感器数据基本能力,主要包含查询传感器的列表、订阅/取消传感器的数据、执行控制命令等。 根据传感器的用途,可以将传感器分为六大类:运动类传感器、环境类传感器、方向类传感器、光线类传感器、健康类传感器、其他类传感器(如霍尔传感器),每一大类传感器包含不同类型的传感器,某种类型的传感器可能是单一的物理传感器,也可能是由多个物理传感器复合而成。 @@ -10,7 +8,7 @@ sensor模块提供订阅传感器数据基本能力,主要包含查询传感 > **说明:** > > - 从API Version 8开始,该接口不再维护,推荐使用新接口[`@ohos.sensor`](js-apis-sensor.md)。 -> - 本模块首批接口从API version 4开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 该功能使用需要对应硬件支持,仅支持真机调试。 @@ -21,15 +19,9 @@ sensor模块提供订阅传感器数据基本能力,主要包含查询传感 import sensor from '@system.sensor'; ``` -## 传感器错误码列表 - -| 错误码 | 说明 | -| ---- | -------------- | -| 900 | 当前设备不支持相应的传感器。 | - ## sensor.subscribeAccelerometer -subscribeAccelerometer(Object): void + subscribeAccelerometer(options: subscribeAccelerometerOptions): void 观察加速度数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -39,23 +31,13 @@ subscribeAccelerometer(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | 是 | 频率参数,加速度的回调函数执行频率。
默认为normal,可选值有:
- game:极高的回调频率,20ms/次,适用于游戏。
- ui:较高的回调频率,60ms/次,适用于UI更新。
- normal:普通的回调频率,200ms/次,低功耗。 | -| success | Function | 是 | 感应到加速度数据变化后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| ---- | ------ | ------- | -| x | number | x轴的加速度。 | -| y | number | y轴的加速度。 | -| z | number | z轴的加速度。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| options | [subscribeAccelerometerOptions](#subscribeaccelerometeroptions) | 是 | 监听加速度传感器数据的回调函数的执行频率。 | **示例:** -``` +```js sensor.subscribeAccelerometer({ interval: 'normal', success: function(ret) { @@ -84,13 +66,13 @@ unsubscribeAccelerometer(): void **示例:** -``` +```js sensor.unsubscribeAccelerometer(); ``` ## sensor.subscribeCompass -subscribeCompass(Object): void + subscribeCompass(options: SubscribeCompassOptions): void 订阅罗盘数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -98,20 +80,13 @@ subscribeCompass(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | --------------- | -| success | Function | 是 | 罗盘数据改变后触发的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| --------- | ------ | ---------- | -| direction | number | 设备面对的方向度数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeCompassOptions](#subscribecompassoptions) | 是 | 当罗盘传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeCompass({ success: function(ret) { console.log('get data direction:' + ret.direction); @@ -135,13 +110,13 @@ unsubscribeCompass(): void **示例:** -``` +```js sensor.unsubscribeCompass(); ``` ## sensor.subscribeProximity -subscribeProximity(Object): void + subscribeProximity(options: SubscribeProximityOptions): void 订阅距离感应数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -149,20 +124,13 @@ subscribeProximity(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | ----------------- | -| success | Function | 是 | 距离感应数据改变后调用的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | ------ | --------------------- | -| distance | number | 可见物体相对于设备显示屏的接近或远离状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeProximityOptions](#subscribeproximityoptions) | 是 | 当距离传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeProximity({ success: function(ret) { console.log('get data distance:' + ret.distance); @@ -186,13 +154,13 @@ unsubscribeProximity(): void **示例:** -``` +```js sensor.unsubscribeProximity(); ``` ## sensor.subscribeLight -sensor.subscribeLight(Object): void + subscribeLight(options: SubscribeLightOptions): void 订阅环境光线感应数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。 @@ -200,20 +168,13 @@ sensor.subscribeLight(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | --------------- | -| success | Function | 是 | 光线感应数据改变后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| --------- | ------ | ------------ | -| intensity | number | 光线强度,单位为lux。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------------------- | ---- | ---------------------------------- | +| options | [SubscribeLightOptions](#subscribelightoptions) | 是 | 当环境光传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeLight({ success: function(ret) { console.log('get data intensity:' + ret.intensity); @@ -237,13 +198,13 @@ unsubscribeLight(): void **示例:** -``` +```js sensor.unsubscribeLight(); ``` ## sensor.subscribeStepCounter -subscribeStepCounter(Object): void + subscribeStepCounter(options: SubscribeStepCounterOptions): void 订阅计步传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -253,20 +214,13 @@ subscribeStepCounter(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | ---------------- | -| success | Function | 是 | 计步传感器数据改变后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| ----- | ------ | --------------------- | -| steps | number | 计步传感器重启后累计记录的步数。
| +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------------------------------- | ---- | -------------------------------------- | +| options | [SubscribeStepCounterOptions](#subscribestepcounteroptions) | 是 | 当步进计数器传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeStepCounter({ success: function(ret) { console.log('get step value:' + ret.steps); @@ -292,14 +246,14 @@ unsubscribeStepCounter(): void **示例:** -``` +```js sensor.unsubscribeStepCounter(); ``` ## sensor.subscribeBarometer -subscribeBarometer(Object): void +subscribeBarometer(options: SubscribeBarometerOptions): void 订阅气压传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -307,20 +261,13 @@ subscribeBarometer(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | ---------------- | -| success | Function | 是 | 气压传感器数据改变后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | ------ | ----------- | -| pressure | number | 气压值,单位:帕斯卡。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------- | ---- | ---------------------------------- | +| options | [SubscribeBarometerOptions](#subscribebarometeroptions) | 是 | 当气压计传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeBarometer({ success: function(ret) { console.log('get data value:' + ret.pressure); @@ -345,14 +292,14 @@ unsubscribeBarometer(): void **示例:** -``` +```js sensor.unsubscribeBarometer(); ``` ## sensor.subscribeHeartRate -subscribeHeartRate(Object): void + subscribeHeartRate(options: SubscribeHeartRateOptions): void 订阅心率传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -362,20 +309,13 @@ subscribeHeartRate(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | ------------------------- | -| success | Function | 是 | 心率传感器数据改变后的回调函数,默认频率5s/次。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| --------- | ------ | ---- | -| heartRate | number | 心率值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------- | ---- | -------------------------------- | +| options | [SubscribeHeartRateOptions](#subscribeheartrateoptions) | 是 | 当心率传感器数据发生变化时调用。 | **示例:** -``` +```js sensor.subscribeHeartRate({ success: function(ret) { console.log('get heartrate value:' + ret.heartRate); @@ -402,13 +342,13 @@ unsubscribeHeartRate(): void **示例:** -``` +```js sensor.unsubscribeHeartRate(); ``` ## sensor.subscribeOnBodyState -subscribeOnBodyState(Object): void + subscribeOnBodyState(options: SubscribeOnBodyStateOptions): void 订阅设备佩戴状态。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 @@ -416,20 +356,13 @@ subscribeOnBodyState(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------- | ---- | ------------- | -| success | Function | 是 | 穿戴状态改变后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| ----- | ------- | ------ | -| value | boolean | 是否已佩戴。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------------------------------- | ---- | ---------------------- | +| options | [SubscribeOnBodyStateOptions](#subscribeonbodystateoptions) | 是 | 当穿着状态改变时调用。 | **示例:** -``` +```js sensor.subscribeOnBodyState({ success: function(ret) { console.log('get on-body state value:' + ret.value); @@ -453,13 +386,13 @@ unsubscribeOnBodyState(): void **示例:** -``` +```js sensor.unsubscribeOnBodyState(); ``` ## sensor.getOnBodyState -getOnBodyState(Object): void + getOnBodyState(options: GetOnBodyStateOptions): void 获取设备佩戴状态。 @@ -467,21 +400,13 @@ getOnBodyState(Object): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------ | -| success | Function | 否 | 接口调用成功的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | -| complete | Function | 否 | 接口调用结束的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| ----- | ------- | ------ | -| value | boolean | 是否已佩戴。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------------------- | ---- | -------------------------- | +| options | [GetOnBodyStateOptions](#getonbodystateoptions) | 是 | 获取传感器磨损状态时调用。 | **示例:** -``` +```js sensor.getOnBodyState({ success: function(ret) { console.log('on body state: ' + ret.value); @@ -494,7 +419,7 @@ sensor.getOnBodyState({ ## sensor.subscribeDeviceOrientation6+ -subscribeDeviceOrientation(interval: string, success: (data: DeviceOrientationResponse), fail?: (data: string, code: number)): void + subscribeDeviceOrientation(options: SubscribeDeviceOrientationOptions): void 观察设备方向传感器数据变化。 @@ -504,22 +429,13 @@ subscribeDeviceOrientation(interval: string, success: (data: DeviceOrientationRe **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | 是 | 频率参数,设备方向传感器的回调函数执行频率。
默认为normal,可选值有:
- game:极高的回调频率,20ms/次,适用于游戏。
- ui:较高的回调频率,60ms/次,适用于UI更新。
- normal:普通的回调频率,200ms/次,低功耗。 | -| success | Function | 是 | 感应到设备方向传感器数据变化后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - - success返回值: -| 参数名 | 类型 | 说明 | -| ----- | ------ | ---------------------------------------- | -| alpha | number | 当设备坐标 X/Y 和地球 X/Y 重合时,绕着 Z 轴转动的夹角为 alpha。 | -| beta | number | 当设备坐标 Y/Z 和地球 Y/Z 重合时,绕着 X 轴转动的夹角为 beta。 | -| gamma | number | 当设备 X/Z 和地球 X/Z 重合时,绕着 Y 轴转动的夹角为 gamma。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| options | [SubscribeDeviceOrientationOptions](#subscribedeviceorientationoptions) | 是 | 用于监听设备方向传感器数据的回调函数的执行频率。 | **示例:** -``` +```js sensor.subscribeDeviceOrientation({ interval: 'normal', success: function(ret) { @@ -546,13 +462,13 @@ unsubscribeDeviceOrientation(): void **示例:** -``` +```js sensor.unsubscribeDeviceOrientation(); ``` ## sensor.subscribeGyroscope6+ -subscribeGyroscope(interval: string, success: (data: GyroscopeResponse), fail?: (data: string, code: number)): void + subscribeGyroscope(options: SubscribeGyroscopeOptions): void 观察陀螺仪数据变化。 @@ -564,23 +480,13 @@ subscribeGyroscope(interval: string, success: (data: GyroscopeResponse), fail?: **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | 是 | 频率参数,陀螺仪的回调函数执行频率。
默认为normal,可选值有:
- game:极高的回调频率,20ms/次,适用于游戏。
- ui:较高的回调频率,60ms/次,适用于UI更新。
- normal:普通的回调频率,200ms/次,低功耗。 | -| success | Function | 是 | 感应到陀螺仪数据变化后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| ---- | ------ | --------- | -| x | number | x轴的旋转角速度。 | -| y | number | y轴的旋转角速度。 | -| z | number | z轴的旋转角速度。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------------------- | ---- | ---------------------------------------------- | +| options | [SubscribeGyroscopeOptions](#subscribegyroscopeoptions) | 是 | 用于侦听陀螺仪传感器数据的回调函数的执行频率。 | **示例:** -``` +```js sensor.subscribeGyroscope({ interval: 'normal', success: function(ret) { @@ -609,6 +515,253 @@ unsubscribeGyroscope(): void **示例:** -``` +```js sensor.unsubscribeGyroscope(); ``` + +## subscribeAccelerometerOptions + +用于监听加速度传感器数据的回调函数的执行频率。 + +**需要权限**:ohos.permission.ACCELEROMETER + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | 是 | 频率参数,加速度的回调函数执行频率。 默认为normal,可选值有: - game:极高的回调频率,20ms/次,适用于游戏。 - ui:较高的回调频率,60ms/次,适用于UI更新。 - normal:普通的回调频率,200ms/次,低功耗。 | +| success | [AccelerometerResponse](#accelerometerresponse) | 是 | 感应到加速度数据变化后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## AccelerometerResponse + +感应到加速度数据变化后的回调函数。 + +**需要权限**:ohos.permission.ACCELEROMETER + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ------------- | +| x | number | 是 | x轴的加速度。 | +| y | number | 是 | y轴的加速度。 | +| z | number | 是 | z轴的加速度。 | + +## SubscribeCompassOptions + +当罗盘传感器数据发生变化时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------- | ---- | ------------------------------ | +| success | [CompassResponse](#compassresponse) | 是 | 罗盘数据改变后触发的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## CompassResponse + +罗盘数据改变后触发的回调函数。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | -------------------- | +| direction | number | 是 | 设备面对的方向度数。 | + +## SubscribeProximityOptions + +当距离传感器数据发生变化时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | --------------------------------------- | ---- | ---------------------------------- | +| success | [ProximityResponse](#proximityresponse) | 是 | 距离感应数据改变后调用的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## ProximityResponse + +距离感应数据改变后调用的回调函数。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------ | +| distance | number | 是 | 可见物体相对于设备显示屏的接近或远离状态。 | + +## SubscribeLightOptions + +当环境光传感器数据发生变化时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------- | ---- | ------------------------------ | +| success | [LightResponse](#lightresponse) | 是 | 光线感应数据改变后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## LightResponse + +光线感应数据改变后的回调函数。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------------------- | +| intensity | number | 是 | 光线强度,单位为lux。 | + +## SubscribeStepCounterOptions + +当步进计数器传感器数据发生变化时调用。 + +**需要权限**:ohos.permission.ACTIVITY_MOTION + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------- | ---- | -------------------------------- | +| success | [StepCounterResponse](#stepcounterresponse) | 是 | 计步传感器数据改变后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## StepCounterResponse + +计步传感器数据改变后的回调函数。 + +**需要权限**:ohos.permission.ACTIVITY_MOTION + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | -------------------------------- | +| steps | number | 是 | 计步传感器重启后累计记录的步数。 | + +## SubscribeBarometerOptions + +当气压计传感器数据发生变化时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | --------------------------------------- | ---- | -------------------------------- | +| success | [BarometerResponse](#barometerresponse) | 是 | 气压传感器数据改变后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## BarometerResponse + +气压传感器数据改变后的回调函数。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------------------- | +| pressure | number | 是 | 气压值,单位:帕斯卡。 | + +## SubscribeHeartRateOptions + +当心率传感器数据发生变化时调用。 + +**需要权限**:ohos.permission.READ_HEALTH_DATA + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | --------------------------------------- | ---- | ----------------------------------------------- | +| success | [HeartRateResponse](#heartrateresponse) | 是 | 心率传感器数据改变后的回调函数,默认频率5s/次。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## HeartRateResponse + +心率传感器数据改变后的回调函数,默认频率5s/次。 + +**需要权限**:ohos.permission.READ_HEALTH_DATA + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | -------- | +| heartRate | number | 是 | 心率值。 | + +## SubscribeOnBodyStateOptions + +当穿着状态改变时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------- | ---- | -------------------------- | +| success | [OnBodyStateResponse](#onbodystateresponse) | 是 | 穿戴状态改变后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## OnBodyStateResponse + +传感器是否磨损。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ----- | ------- | ---- | ------------ | +| value | boolean | 是 | 是否已佩戴。 | + +## GetOnBodyStateOptions + + 获取传感器磨损状态时调用。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ------------------------ | +| success | [OnBodyStateResponse](#onbodystateresponse) | 否 | 接口调用成功的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | +| complete | Function | 否 | 接口调用结束的回调函数。 | + +## SubscribeDeviceOrientationOptions6+ + +用于监听设备方向传感器数据的回调函数的执行频率。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | 是 | 频率参数,设备方向传感器的回调函数执行频率。
默认为normal,可选值有:
- game:极高的回调频率,20ms/次,适用于游戏。
- ui:较高的回调频率,60ms/次,适用于UI更新。
- normal:普通的回调频率,200ms/次,低功耗。 | +| success | [DeviceOrientationResponse](#deviceorientationresponse) | 是 | 感应到设备方向传感器数据变化后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## DeviceOrientationResponse6+ + +感应到设备方向传感器数据变化后的回调函数。 + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ------------------------------------------------------------ | +| alpha | number | 是 | 当设备坐标 X/Y 和地球 X/Y 重合时,绕着 Z 轴转动的夹角为 alpha。 | +| beta | number | 是 | 当设备坐标 Y/Z 和地球 Y/Z 重合时,绕着 X 轴转动的夹角为 beta。 | +| gamma | number | 是 | 当设备 X/Z 和地球 X/Z 重合时,绕着 Y 轴转动的夹角为 gamma。 | + +## SubscribeGyroscopeOptions6+ + +用于侦听陀螺仪传感器数据的回调函数的执行频率。 + +**需要权限**:ohos.permission.GYROSCOPE + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| interval | string | 是 | 频率参数,陀螺仪的回调函数执行频率。
默认为normal,可选值有:
- game:极高的回调频率,20ms/次,适用于游戏。
- ui:较高的回调频率,60ms/次,适用于UI更新。
- normal:普通的回调频率,200ms/次,低功耗。 | +| success | [GyroscopeResponse](#gyroscoperesponse) | 是 | 感应到陀螺仪数据变化后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | + +## GyroscopeResponse6+ + +感应到陀螺仪数据变化后的回调函数。 + +**需要权限**:ohos.permission.GYROSCOPE + +**系统能力**:SystemCapability.Sensors.Sensor + +| 名称 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ----------------- | +| x | number | 是 | x轴的旋转角速度。 | +| y | number | 是 | y轴的旋转角速度。 | +| z | number | 是 | z轴的旋转角速度。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md index 0d8e3958c0847d20639ed13991919981a6bdcb84..7726086cc4e0c4e0327b773d8278e9240fcb5041 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @@ -1,14 +1,12 @@ # @system.vibrator (振动) -## 模块说明 - vibrator模块提供控制马达振动的能力,主要包含灯的列表查询、打开灯、关闭灯等接口,振动器的列表查询、振动器的振动器效果查询、触发/关闭振动器等接口。 控制类小器件指的是设备上的LED灯和振动器。其中,LED灯主要用作指示(如充电状态)、闪烁功能(如三色灯)等;振动器主要用于闹钟、开关机振动、来电振动等场景。 > **说明:** -> - 本模块首批接口从API version 4开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 从API Version 8开始,该接口不再维护,推荐使用新接口[`@ohos.vibrator`](js-apis-vibrator.md)。 > - 该功能使用需要对应硬件支持,仅支持真机调试。 @@ -22,26 +20,23 @@ import vibrator from '@system.vibrator'; ## vibrator.vibrate -vibrate(Object): void + vibrate(options?: VibrateOptions): void 触发设备振动。 -**系统能力**:SystemCapability.Sensors.MiscDevice +**需要权限**:ohos.permission.VIBRATE -**需要权限**:ohos.permission.VIBRATE,该权限为系统权限 +**系统能力**:SystemCapability.Sensors.MiscDevice **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| mode | string | 否 | 振动的模式,其中long表示长振动,short表示短振动,默认值为long。 | -| success | Function | 是 | 感应到振动数据变化后的回调函数。 | -| fail | Function | 否 | 接口调用失败的回调函数。 | -| complete | Function | 否 | 接口调用结束的回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------------- | ---- | ---------- | +| options | [VibrateOptions](#vibrateoptions) | 否 | 振动模式。 | **示例:** -``` +```js vibrator.vibrate({ mode: 'short', success: function() { @@ -56,3 +51,17 @@ vibrator.vibrate({ }); ``` +## VibrateOptions + +振动模式。 + +**需要权限**:ohos.permission.VIBRATE + +**系统能力**:SystemCapability.Sensors.MiscDevice + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| mode | string | 否 | 振动的模式,其中long表示长振动,short表示短振动,默认值为long。 | +| success | Function | 否 | 感应到振动数据变化后的回调函数。 | +| fail | Function | 否 | 接口调用失败的回调函数。 | +| complete | Function | 否 | 接口调用结束的回调函数。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md b/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md index 3b47746d554cb7d47e7d0ac83c9089ca2990dda9..2f2c9114c9a42d702d1ab67ecc9f068ac640c5c0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md +++ b/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @@ -85,7 +85,7 @@ setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): v 设置默认移动数据的SIM卡,使用callback方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -125,7 +125,7 @@ setDefaultCellularDataSlotId(slotId: number): Promise\ 设置默认移动数据的SIM卡,使用Promise方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -420,7 +420,7 @@ enableCellularData(callback: AsyncCallback): void 启用蜂窝数据服务,使用callback方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -457,7 +457,7 @@ enableCellularData(): Promise 启用蜂窝数据服务,使用Promise方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -497,7 +497,7 @@ disableCellularData(callback: AsyncCallback): void 禁用蜂窝数据服务,使用callback方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -534,7 +534,7 @@ disableCellularData(): Promise 禁用蜂窝数据服务,使用Promise方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -574,7 +574,7 @@ enableCellularDataRoaming(slotId: number, callback: AsyncCallback): void 启用蜂窝数据漫游,使用callback方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -612,7 +612,7 @@ enableCellularDataRoaming(slotId: number): Promise 启用蜂窝数据漫游,使用Promise方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -658,7 +658,7 @@ disableCellularDataRoaming(slotId: number, callback: AsyncCallback): void 禁用蜂窝数据漫游,使用callback方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -696,7 +696,7 @@ disableCellularDataRoaming(slotId: number): Promise 禁用蜂窝数据漫游,使用Promise方式作为异步方法。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **需要权限**:ohos.permission.SET_TELEPHONY_STATE @@ -740,7 +740,7 @@ promise.then((data) => { 描述蜂窝数据流类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CellularData。 +**系统能力**:SystemCapability.Telephony.CellularData | 名称 | 值 | 说明 | | ---------------------- | ---- | ------------------------------------------ | @@ -754,7 +754,7 @@ promise.then((data) => { 描述蜂窝数据链路连接状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CellularData。 +**系统能力**:SystemCapability.Telephony.CellularData | 名称 | 值 | 说明 | | ----------------------- | ---- | -------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md new file mode 100644 index 0000000000000000000000000000000000000000..28402007b002e0f214060f8dc9a629d2d042a311 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @@ -0,0 +1,106 @@ +# 用户界面外观 + +用户界面外观提供管理系统外观的一些基础能力,目前仅包括深浅色模式配置。 + +> **说明:** +> +> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 本模块接口为系统接口。 + + +## 导入模块 + +```ts +import uiAppearance from '@ohos.uiAppearance' +``` + + +## DarkMode + +深色模式枚举。 + + +**系统能力:** SystemCapability.ArkUI.UiAppearance + +| 名称 | 值 | 说明 | +| -- | -- | -- | +| ALWAYS_DARK | 0 | 系统始终为深色。 | +| ALWAYS_LIGHT | 1 | 系统始终为浅色。 | + + +## uiAppearance.setDarkMode + +setDarkMode(mode: DarkMode, callback: AsyncCallback\): void + +设置系统深色模式。 + +**需要权限:** ohos.permission.UPDATE_CONFIGURATION + +**系统能力:** SystemCapability.ArkUI.UiAppearance + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -- | -- | -- | -- | +| mode | [DarkMode](#darkmode) | 是 | 指定系统的深色模式配置 | +| callback | AsyncCallback\| 是 | 配置深色模式的异步回调 | + +**示例:** + ```ts +uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK, (err) => { + console.info(`${err}`); +}) + ``` + + +## uiAppearance.setDarkMode + +setDarkMode(mode: DarkMode): Promise\; + +设置系统深色模式。 + +**需要权限:** ohos.permission.UPDATE_CONFIGURATION + +**系统能力:** SystemCapability.ArkUI.UiAppearance + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -- | -- | -- | -- | +| mode | [DarkMode](#darkmode) | 是 | 指定系统深色模式配置 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象。| + +**示例:** + ```ts +uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK).then(() => { + console.log('Set dark-mode successfully.'); +}).catch((err) => { + console.log(`Set dark-mode failed, ${err}`); +}); + ``` + + +## uiAppearance.getDarkMode + +getDarkMode(): DarkMode; + +获取当前的深色模式配置。 + +**需要权限:** ohos.permission.UPDATE_CONFIGURATION + +**系统能力:** SystemCapability.ArkUI.UiAppearance + +**返回值:** +| 类型 | 说明 | +| -- | -- | +|[DarkMode](#darkmode) | 系统当前的深色模式配置 | + +**示例:** + ```ts +let darkMode = uiAppearance.getDarkMode(); +console.log(`Get dark-mode ${darkMode}`); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-UiTest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md similarity index 92% rename from zh-cn/application-dev/reference/apis/js-apis-UiTest.md rename to zh-cn/application-dev/reference/apis/js-apis-uitest.md index f04ccc898c1e3f61c1dfe47d01a89a9b3ca89e71..46f766d853ce0331c15e26d6d4f936800b698289 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-UiTest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -1,4 +1,4 @@ -# @ohos.UiTest (UiTest) +# @ohos.UiTest UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要支持如点击、双击、长按、滑动等UI操作能力。 @@ -20,7 +20,7 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 ## 导入模块 ```js -import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest'; +import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix, UiDirection, MouseButton} from '@ohos.UiTest'; ``` ## MatchPattern @@ -79,10 +79,10 @@ import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern ## WindowMode9+ -**系统能力**:SystemCapability.Test.UiTest - 窗口的窗口模式。 +**系统能力**:SystemCapability.Test.UiTest + | 名称 | 值 | 说明 | | ---------- | ---- | ---------- | | FULLSCREEN | 0 | 全屏模式。 | @@ -92,10 +92,10 @@ import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern ## DisplayRotation9+ -**系统能力**:SystemCapability.Test.UiTest - 设备显示器的显示方向。 +**系统能力**:SystemCapability.Test.UiTest + | 名称 | 值 | 说明 | | ------------ | ---- | ---------------------------------------- | | ROTATION_0 | 0 | 设备显示器不旋转,初始形态垂直显示。 | @@ -116,6 +116,31 @@ import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern | focused | boolean | 是 | 否 | 窗口是否处于获焦状态。 | | actived | boolean | 是 | 否 | 窗口是否正与用户进行交互。 | +## UiDirection10+ + +进行抛滑等UI操作时的方向。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 值 | 说明 | +| ----- | ---- | ------ | +| LEFT | 0 | 向左。 | +| RIGHT | 1 | 向右。 | +| UP | 2 | 向上。 | +| DOWN | 3 | 向下。 | + +## MouseButton10+ + +模拟注入的鼠标按钮。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 值 | 说明 | +| ------------------- | ---- | ------------ | +| MOUSE_BUTTON_LEFT | 0 | 鼠标左键。 | +| MOUSE_BUTTON_RIGHT | 1 | 鼠标右键。 | +| MOUSE_BUTTON_MIDDLE | 2 | 鼠标中间键。 | + ## On9+ UiTest框架在API 9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
@@ -468,6 +493,58 @@ isAfter(on: On): On let on = ON.isAfter(ON.text('123')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之后。 ``` +### within10+ + +within(on: On): On + +指定目标控件位于给出的特征属性控件之内,返回On对象自身。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | 是 | 特征控件的属性要求。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------------------------------------- | +| [On](#on9) | 返回指定目标控件位于给出的特征属性控件内的On对象。 | + +**示例:** + +```js +let on = ON.within(ON.type('List')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之内。 +``` + +### inWindow10+ + +inWindow(bundleName: string): On; + +指定目标控件位于给出的应用窗口内,返回On对象自身。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ---------------- | +| bundleName | string | 是 | 应用窗口的包名。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ---------------------------------------------- | +| [On](#on9) | 返回指定目标控件位于给出的应用窗口内的On对象。 | + +**示例:** + +```js +let on = ON.inWindow(ON.inWindow('com.uitestScene.acts')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的应用窗口内。 +``` + ## Component9+ UiTest框架在API9中,Component类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 @@ -1816,7 +1893,7 @@ Driver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 ```js async function demo() { let driver = Driver.create(); - await driver.screenCap('/local/tmp/1.png'); + await driver.screenCap('/data/storage/el2/base/cache/1.png'); } ``` @@ -2078,7 +2155,7 @@ fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ | from | [Point](#point9) | 是 | 手指接触屏幕的起始点坐标。 | | to | [Point](#point9) | 是 | 手指离开屏幕时的坐标点。 | | stepLen | number | 是 | 间隔距离,单位:像素点。 | -| speed | number | 是 | 滑动速率,范围:200-15000,不在范围内设为默认值为600,单位:像素点/秒。 | +| speed | number | 是 | 滑动速率,范围:200-40000,不在范围内设为默认值为600,单位:像素点/秒。 | **错误码:** @@ -2093,7 +2170,7 @@ fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ ```js async function demo() { let driver = Driver.create(); - await driver.fling({X: 500, Y: 480},{X: 450, Y: 480},5,600); + await driver.fling({x: 500, y: 480},{x: 450, y: 480},5,600); } ``` @@ -2132,16 +2209,186 @@ injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\10+
+ +fling(direction: UiDirection, speed: number): Promise; + +指定方向和速度,模拟手指滑动后脱离屏幕的快速滑动操作。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| direction | [UiDirection](#uidirection10) | 是 | 进行抛滑的方向。 | +| speed | number | 是 | 滑动速率,范围:200-40000,不在范围内设为默认值为600,单位:像素点/秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**示例:** + +```js +async function demo() { + let driver = Driver.create(); + await driver.fling(UiDirection.DOWN, 10000); +} +``` + +### screenCapture10+ + +screenCapture(savePath: string, rect?: Rect): Promise; + +捕获当前屏幕的指定区域,并保存为PNG格式的图片至给出的保存路径中。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------- | ---- | ---------------------- | +| savePath | string | 是 | 文件保存路径。 | +| rect | [Rect](#rect9) | 否 | 截图区域,默认为全屏。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------------- | +| Promise\ | 截图操作是否成功完成。成功完成为true。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**示例:** + +```js +async function demo() { + let driver = Driver.create(); + await driver.screenCapture('/data/storage/el2/base/cache/1.png', {left: 0, top: 0, right: 100, bottom: 100}); +} +``` + +### mouseClick10+ + +mouseClick(p: Point, btnId: MouseButton, key1?: number, key2?: number): Promise; + +在指定坐标点注入鼠标点击动作,支持同时按下对应键盘组合键。例如,Key值为2072时,按下ctrl并进行鼠标点击动作。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------- | ---- | ------------------- | +| p | [Point](#point9) | 是 | 鼠标点击的坐标。 | +| btnId | [MouseButton](#mousebutton10) | 是 | 按下的鼠标按钮。 | +| 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 = Driver.create(); + await driver.mouseClick({x:248, y:194}, MouseButton.MOUSE_BUTTON_LEFT, 2072); +} +``` + +### mouseScroll10+ + +mouseScroll(p: Point, down: boolean, d: number, key1?: number, key2?: number): Promise; + +在指定坐标点注入鼠标滚轮滑动动作,支持同时按下对应键盘组合键。例如,Key值为2072时,按下ctrl并进行鼠标滚轮滑动动作。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------- | ---- | --------------------------------------------------- | +| p | [Point](#point9) | 是 | 鼠标点击的坐标。 | +| down | boolean | 是 | 滚轮滑动方向是否向下。 | +| d | number | 是 | 鼠标滚轮滚动的格数,每格对应目标点位移120个像素点。 | +| 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 = Driver.create(); + await driver.mouseScroll({x:360, y:640}, true, 30, 2072) +} +``` + +### mouseMoveTo10+ + +mouseMoveTo(p: Point): Promise; + +将鼠标光标移到目标点。 + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------- | ---- | -------------- | +| p | [Point](#point9) | 是 | 目标点的坐标。 | + +**错误码:** + +以下错误码的详细介绍请参见[uitest测试框架错误码](../errorcodes/errorcode-uitest.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**示例:** + +```js +async function demo() { + let driver = Driver.create(); + await driver.mouseMoveTo({x:100, y:100}) +} +``` + ## PointerMatrix9+ 存储多指操作中每根手指每一步动作的坐标点及其行为的二维数组。 @@ -2196,12 +2443,12 @@ setPoint(finger: number, step: number, point: Point): void ```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}); + 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}); } ``` @@ -3673,6 +3920,6 @@ UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 ```js async function demo() { let driver = UiDriver.create(); - await driver.screenCap('/local/tmp/1.png'); + await driver.screenCap('/data/storage/el2/base/cache/1.png'); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-update.md b/zh-cn/application-dev/reference/apis/js-apis-update.md index 144bb69c2bbef40ef5605b4ab7883475b3eb8970..e2aa8974228692c77c455a1276bfa002f3b8b61c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-update.md +++ b/zh-cn/application-dev/reference/apis/js-apis-update.md @@ -2036,7 +2036,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | WAITING_INSTALL | 30 | 待安装。 | | UPDATING | 31 | 更新中。 | | WAITING_APPLY | 40 | 待生效。 | -| APPLYING | 21 | 生效中。 | +| APPLYING | 41 | 生效中。 | | UPGRADE_SUCCESS | 50 | 升级成功。 | | UPGRADE_FAIL | 51 | 升级失败。 | @@ -2058,7 +2058,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 值 | 说明 | | ---------------------- | ---------- | ------ | -| EVENT_TASK_BASE | 0x01000000 | 任务事件。 | +| EVENT_TASK_BASE | EventClassify.TASK | 任务事件。 | | EVENT_TASK_RECEIVE | 0x01000001 | 收到任务。 | | EVENT_TASK_CANCEL | 0x01000010 | 取消任务。 | | EVENT_DOWNLOAD_WAIT | 0x01000011 | 待下载。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md b/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md index 8cfdfad79d999541c7aa89f26a00b738a76ea06b..90a86e2c1b414f4509e807450837cc3952045da0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -32,7 +32,7 @@ getDevices(): Array<Readonly<USBDevice>> ```js let devicesList = usb.getDevices(); -console.log(`devicesList = ${JSON.stringify(devicesList)}`); +console.log(`devicesList = ${devicesList}`); //devicesList 返回的数据结构 //此处提供一个简单的示例,如下 [ @@ -111,7 +111,7 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> ```js let devicepipe= usb.connectDevice(device); -console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +console.log(`devicepipe = ${devicepipe}`); ``` ## usb.hasRight @@ -167,7 +167,7 @@ requestRight(deviceName: string): Promise<boolean> ```js let devicesName="1-1"; usb.requestRight(devicesName).then((ret) => { - console.log(`requestRight = ${JSON.stringify(ret)}`); + console.log(`requestRight = ${ret}`); }); ``` @@ -375,8 +375,9 @@ controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: **示例:** ```js -usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { - console.log(`controlTransfer = ${JSON.stringify(ret)}`); +let param = new usb.USBControlParams(); +usb.controlTransfer(devicepipe, param).then((ret) => { + console.log(`controlTransfer = ${ret}`); }) ``` @@ -412,7 +413,7 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim //把获取到的设备对象作为参数传入usb.connectDevice;当usb.connectDevice接口成功返回之后; //才可以调用第三个接口usb.claimInterface.当usb.claimInterface 调用成功以后,再调用该接口。 usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { - console.log(`bulkTransfer = ${JSON.stringify(ret)}`); + console.log(`bulkTransfer = ${ret}`); }); ``` @@ -499,7 +500,7 @@ usbFunctionsToString(funcs: FunctionType): string **示例:** ```js -let funcs = ACM | ECM; +let funcs = usb.ACM | usb.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -528,7 +529,7 @@ setCurrentFunctions(funcs: FunctionType): Promise\ **示例:** ```js -let funcs = HDC; +let funcs = usb.HDC; let ret = usb.setCurrentFunctions(funcs); ``` @@ -631,7 +632,12 @@ setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): **示例:** ```js -let ret = usb.getSupportedModes(0); +let portId = 1; +usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { + console.info('usb setPortRoles successfully.'); +}).catch(err => { + console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); +}); ``` ## USBEndpoint diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb.md b/zh-cn/application-dev/reference/apis/js-apis-usb.md index dbc589203251e74a0158365d73da639edd0d48a8..df58b15f33dd1b1668795996d324ca2aeeedd347 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usb.md @@ -32,7 +32,7 @@ getDevices(): Array<Readonly<USBDevice>> ```js let devicesList = usb.getDevices(); -console.log(`devicesList = ${JSON.stringify(devicesList)}`); +console.log(`devicesList = ${devicesList}`); //devicesList 返回的数据结构 //此处提供一个简单的示例,如下 [ @@ -121,13 +121,12 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> let devicesList = usb.getDevices(); if (devicesList.length == 0) { console.log(`device list is empty`); - return; } let device = devicesList[0]; usb.requestRight(device.name); let devicepipe = usb.connectDevice(device); -console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +console.log(`devicepipe = ${devicepipe}`); ``` ## usb.hasRight @@ -185,7 +184,7 @@ requestRight(deviceName: string): Promise<boolean> ```js let devicesName="1-1"; usb.requestRight(devicesName).then((ret) => { - console.log(`requestRight = ${JSON.stringify(ret)}`); + console.log(`requestRight = ${ret}`); }); ``` @@ -213,7 +212,7 @@ removeRight(deviceName: string): boolean ```js let devicesName="1-1"; -if (usb.removeRight(devicesName) { +if usb.removeRight(devicesName) { console.log(`Succeed in removing right`); } ``` @@ -248,7 +247,7 @@ addRight(bundleName: string, deviceName: string): boolean ```js let devicesName = "1-1"; let bundleName = "com.example.hello"; -if (usb.addRight(bundleName, devicesName) { +if usb.addRight(bundleName, devicesName) { console.log(`Succeed in adding right`); } ``` @@ -457,8 +456,9 @@ controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: **示例:** ```js -usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { - console.log(`controlTransfer = ${JSON.stringify(ret)}`); +let param = new usb.USBControlParams(); +usb.controlTransfer(devicepipe, param).then((ret) => { + console.log(`controlTransfer = ${ret}`); }) ``` @@ -494,7 +494,7 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim //把获取到的设备对象作为参数传入usb.connectDevice;当usb.connectDevice接口成功返回之后; //才可以调用第三个接口usb.claimInterface.当usb.claimInterface 调用成功以后,再调用该接口。 usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { - console.log(`bulkTransfer = ${JSON.stringify(ret)}`); + console.log(`bulkTransfer = ${ret}`); }); ``` @@ -581,7 +581,7 @@ usbFunctionsToString(funcs: FunctionType): string **示例:** ```js -let funcs = ACM | ECM; +let funcs = usb.ACM | usb.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -610,7 +610,7 @@ setCurrentFunctions(funcs: FunctionType): Promise\ **示例:** ```js -let funcs = HDC; +let funcs = usb.HDC; usb.setCurrentFunctions(funcs).then(() => { console.info('usb setCurrentFunctions successfully.'); }).catch(err => { @@ -718,7 +718,7 @@ setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): ```js let portId = 1; -usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { +usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { console.info('usb setPortRoles successfully.'); }).catch(err => { console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); diff --git a/zh-cn/application-dev/reference/apis/js-apis-usbManager.md b/zh-cn/application-dev/reference/apis/js-apis-usbManager.md index 6eaf7501cc163afbec26e8b9749da044f94b4e05..5b8d67b962b11b834dda0bfe4d14edbcf39a4b61 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usbManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usbManager.md @@ -30,7 +30,7 @@ getDevices(): Array<Readonly<USBDevice>> ```js let devicesList = usb.getDevices(); -console.log(`devicesList = ${JSON.stringify(devicesList)}`); +console.log(`devicesList = ${devicesList}`); //devicesList 返回的数据结构 //此处提供一个简单的示例,如下 [ @@ -119,13 +119,12 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> let devicesList = usb.getDevices(); if (devicesList.length == 0) { console.log(`device list is empty`); - return; } let device = devicesList[0]; usb.requestRight(device.name); let devicepipe = usb.connectDevice(device); -console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +console.log(`devicepipe = ${devicepipe}`); ``` ## usb.hasRight @@ -155,7 +154,7 @@ hasRight(deviceName: string): boolean ```js let devicesName="1-1"; let bool = usb.hasRight(devicesName); -console.log(bool); +console.log(`${bool}`); ``` ## usb.requestRight @@ -183,7 +182,7 @@ requestRight(deviceName: string): Promise<boolean> ```js let devicesName="1-1"; usb.requestRight(devicesName).then((ret) => { - console.log(`requestRight = ${JSON.stringify(ret)}`); + console.log(`requestRight = ${ret}`); }); ``` @@ -211,7 +210,7 @@ removeRight(deviceName: string): boolean ```js let devicesName="1-1"; -if (usb.removeRight(devicesName) { +if usb.removeRight(devicesName) { console.log(`Succeed in removing right`); } ``` @@ -246,7 +245,7 @@ addRight(bundleName: string, deviceName: string): boolean ```js let devicesName = "1-1"; let bundleName = "com.example.hello"; -if (usb.addRight(bundleName, devicesName) { +if usb.addRight(bundleName, devicesName) { console.log(`Succeed in adding right`); } ``` @@ -455,8 +454,9 @@ controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: **示例:** ```js -usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { - console.log(`controlTransfer = ${JSON.stringify(ret)}`); +let param = new usb.USBControlParams(); +usb.controlTransfer(devicepipe, param).then((ret) => { + console.log(`controlTransfer = ${ret}`); }) ``` @@ -492,7 +492,7 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim //把获取到的设备对象作为参数传入usb.connectDevice;当usb.connectDevice接口成功返回之后; //才可以调用第三个接口usb.claimInterface.当usb.claimInterface 调用成功以后,再调用该接口。 usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { - console.log(`bulkTransfer = ${JSON.stringify(ret)}`); + console.log(`bulkTransfer = ${ret}`); }); ``` @@ -579,7 +579,7 @@ usbFunctionsToString(funcs: FunctionType): string **示例:** ```js -let funcs = ACM | ECM; +let funcs = usb.ACM | usb.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -608,7 +608,7 @@ setCurrentFunctions(funcs: FunctionType): Promise\ **示例:** ```js -let funcs = HDC; +let funcs = usb.HDC; usb.setCurrentFunctions(funcs).then(() => { console.info('usb setCurrentFunctions successfully.'); }).catch(err => { @@ -716,7 +716,7 @@ setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): ```js let portId = 1; -usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { +usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { console.info('usb setPortRoles successfully.'); }).catch(err => { console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); diff --git a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md index 251d446bdb9f8250d97fb8e57ef3821f40248522..c7ca4781f1471cb644fe477972ac8bc0604fe88d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -22,8 +22,8 @@ import userIAM_userAuth from '@ohos.userIAM.userAuth'; | ------------ | ---------- | ---- | -------------------- | | result | number | 是 | 认证结果。 | | token | Uint8Array | 否 | 用户身份认证通过的凭证。 | -| remainAttempts | number | 否 | 剩余的认证操作次数。 | -| lockoutDuration | number | 否 | 认证操作的冻结时间。 | +| remainAttempts | number | 否 | 剩余的认证尝试次数。 | +| lockoutDuration | number | 否 | 认证操作的锁定时长,时间单位为毫秒ms。 | ## TipInfo9+ @@ -399,44 +399,6 @@ try { } ``` -## userIAM_userAuth.getVersion9+ - -getVersion(): number - -获取认证器的版本信息。 - -**需要权限**:ohos.permission.ACCESS_BIOMETRIC - -**系统能力**:SystemCapability.UserIAM.UserAuth.Core - -**返回值:** - -| 类型 | 说明 | -| ------ | ---------------------- | -| number | 认证器版本信息。 | - -以下错误码的详细介绍请参见[用户认证错误码](../errorcodes/errorcode-useriam.md) - -**错误码:** - -| 错误码ID | 错误信息 | -| -------- | ------- | -| 201 | Permission verification failed. | -| 12500002 | General operation error. | - -**示例:** - -```js -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); -} catch (error) { - console.info("get version failed, error = " + error); -} -``` - ## userIAM_userAuth.getAvailableStatus9+ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void @@ -535,7 +497,7 @@ getVersion() : number 获取认证器的版本信息。 > **说明:** -> 从 API version 8 开始支持,从 API version 9 开始废弃,请使用[getVersion](#useriam_userauthgetversion9)替代。 +> 从 API version 8 开始支持,从 API version 9 开始废弃。 **需要权限**:ohos.permission.ACCESS_BIOMETRIC diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 0254aca1a63d8d2086da50f893b1c9b2f657d8c9..1e097c20cf4559465ffacc7414865f36db4162fc 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -110,7 +110,7 @@ async function fn() { return 'hello world'; } let cb = util.callbackWrapper(fn); -cb((err, ret) => { +cb(1, (err, ret) => { if (err) throw err; console.log(ret); }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md index c21feac3f1d6302352458849818b1045ee5bb743..4e303338a684f26a0c8ba6dc9d8d0ecb0b4d58e5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @@ -14,7 +14,7 @@ import wallpaper from '@ohos.wallpaper'; ``` -## WallpaperType +## WallpaperType7+ 定义壁纸的枚举类型。 @@ -26,12 +26,14 @@ import wallpaper from '@ohos.wallpaper'; | WALLPAPER_LOCKSCREEN | 1 |锁屏壁纸标识。 | -## RgbaColor +## RgbaColor9+ 定义壁纸颜色信息结构。 **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | red | number | 是 | 是 | 表示红色值,范围为 0 到 255。 | @@ -48,6 +50,8 @@ getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -71,37 +75,6 @@ try { } ``` -## wallpaper.getIdSync9+ - -getIdSync(wallpaperType: WallpaperType): number - -获取指定类型壁纸的ID。 - -**系统能力**: SystemCapability.MiscServices.Wallpaper - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 | - -**返回值**: - -| 类型 | 说明 | -| -------- | -------- | -| number | 返回壁纸的ID。如果配置了这种壁纸类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1到(2^31-1)。 | - -**示例**: - -```js -try { - let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - console.log(`success to getIdSync: ${JSON.stringify(id)}`); -} catch (error) { - console.error(`failed to getIdSync because: ${JSON.stringify(error)}`); -} -``` - ## wallpaper.getMinHeightSync9+ getMinHeightSync(): number @@ -110,6 +83,8 @@ getMinHeightSync(): number **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **返回值:** | 类型 | 说明 | @@ -130,6 +105,8 @@ getMinWidthSync(): number **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **返回值:** | 类型 | 说明 | @@ -142,46 +119,6 @@ getMinWidthSync(): number let minWidth = wallpaper.getMinWidthSync(); ``` -## wallpaper.isChangeAllowed9+ - -isChangeAllowed(): boolean - -是否允许应用改变当前用户的壁纸。 - -**系统能力**: SystemCapability.MiscServices.Wallpaper - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| boolean | 返回是否允许应用改变当前用户的壁纸。如果允许返回true,否则返回false。 | - -**示例:** - -```js -let isChangeAllowed = wallpaper.isChangeAllowed(); -``` - -## wallpaper.isUserChangeAllowed9+ - -isUserChangeAllowed(): boolean - -是否允许用户设置壁纸。 - -**系统能力**: SystemCapability.MiscServices.Wallpaper - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| boolean | 返回是否允许用户设置壁纸。如果允许返回true,否则返回false。 | - -**示例:** - -```js -let isUserChangeAllowed = wallpaper.isUserChangeAllowed(); -``` - ## wallpaper.restore9+ restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void @@ -192,6 +129,8 @@ restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -221,6 +160,8 @@ restore(wallpaperType: WallpaperType): Promise<void> **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -253,6 +194,8 @@ setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -306,6 +249,8 @@ setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise **系统能力**: SystemCapability.MiscServices.Wallpaper +**系统接口**:此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -350,39 +295,6 @@ imageSource.createPixelMap(opts).then((pixelMap) => { }); ``` -## wallpaper.getFileSync9+ - -getFileSync(wallpaperType: WallpaperType): number; - -获取指定类型的壁纸文件。 - -**需要权限**:ohos.permission.GET_WALLPAPER - -**系统能力**: SystemCapability.MiscServices.Wallpaper - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| number | 调用成功则返回壁纸文件描述符ID,调用失败则返回error信息。 | - -**示例:** - -```js -try { - let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - console.log(`success to getFileSync: ${JSON.stringify(file)}`); -} catch (error) { - console.error(`failed to getFileSync because: ${JSON.stringify(error)}`); -} -``` - ## wallpaper.getImage9+ getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; @@ -449,12 +361,16 @@ wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { }); ``` -## wallpaper.on('colorChange')9+ +## wallpaper.on('colorChange')(deprecated) on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void 订阅壁纸颜色变化结果上报事件。 +> **说明:** +> +> 从 API version 7开始支持,从API version 9开始废弃。 + **系统能力**: SystemCapability.MiscServices.Wallpaper **参数:** @@ -477,12 +393,16 @@ try { } ``` -## wallpaper.off('colorChange')9+ +## wallpaper.off('colorChange')(deprecated) off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void 取消订阅壁纸颜色变化结果上报事件。 +> **说明:** +> +> 从 API version 7开始支持,从API version 9开始废弃。 + **系统能力**: SystemCapability.MiscServices.Wallpaper **参数:** @@ -527,7 +447,7 @@ getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<Rgba > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getColorsSync9+](#wallpapergetcolorssync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -558,7 +478,7 @@ getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getColorsSync9+](#wallpapergetcolorssync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -592,7 +512,7 @@ getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getIdSync9+](#wallpapergetidsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -623,7 +543,7 @@ getId(wallpaperType: WallpaperType): Promise<number> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getIdSync9+](#wallpapergetidsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -657,7 +577,7 @@ getMinHeight(callback: AsyncCallback<number>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -687,7 +607,7 @@ getMinHeight(): Promise<number> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -715,7 +635,7 @@ getMinWidth(callback: AsyncCallback<number>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -745,7 +665,7 @@ getMinWidth(): Promise<number> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -773,7 +693,7 @@ isChangePermitted(callback: AsyncCallback<boolean>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -803,7 +723,7 @@ isChangePermitted(): Promise<boolean> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -831,7 +751,7 @@ isOperationAllowed(callback: AsyncCallback<boolean>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -861,7 +781,7 @@ isOperationAllowed(): Promise<boolean> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **系统能力**: SystemCapability.MiscServices.Wallpaper @@ -889,7 +809,7 @@ reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.restore9+](#wallpaperrestore9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -922,7 +842,7 @@ reset(wallpaperType: WallpaperType): Promise<void> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.restore9+](#wallpaperrestore9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -958,7 +878,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, call > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.setImage9+](#wallpapersetimage9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -1015,7 +935,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Pro > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.setImage9+](#wallpapersetimage9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -1074,7 +994,7 @@ getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): vo > **说明:** > -> 从 API version 8开始支持,从API version 9开始废弃。建议使用[wallpaper.getFileSync9+](#wallpapergetfilesync9)代替。 +> 从 API version 8开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.GET_WALLPAPER @@ -1107,7 +1027,7 @@ getFile(wallpaperType: WallpaperType): Promise<number> > **说明:** > -> 从 API version 8开始支持,从API version 9开始废弃。建议使用[wallpaper.getFileSync9+](#wallpapergetfilesync9)代替。 +> 从 API version 8开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.GET_WALLPAPER @@ -1143,7 +1063,7 @@ getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.Pixel > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getImage9+](#wallpapergetimage9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.GET_WALLPAPER @@ -1178,7 +1098,7 @@ getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃。建议使用[wallpaper.getImage9+](#wallpapergetimage9)代替。 +> 从 API version 7开始支持,从API version 9开始废弃。 **需要权限**:ohos.permission.GET_WALLPAPER diff --git a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md index 318a37a9735cabd2ad566542c7783eec2dfeb621..e9cf45b13c404c672dea9facc48b922f3f54da92 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @@ -12,6 +12,145 @@ WantAgent模块提供了创建WantAgent实例、获取实例的用户ID、获取 import WantAgent from '@ohos.wantAgent'; ``` +## WantAgent.getWant + +getWant(agent: WantAgent, callback: AsyncCallback\): void + +获取WantAgent中的Want(callback形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------- | ---- | ----------------------- | +| agent | [WantAgent](js-apis-wantAgent.md) | 是 | WantAgent信息。 | +| callback | AsyncCallback\ | 是 | 获取WantAgent中的Want的回调方法。 | + +**示例:** + +```ts +import WantAgent from '@ohos.wantAgent'; + + +//wantAgent对象 +let wantAgent; + +//getWantAgent回调 +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; + } + + //getWant回调 + function getWantCallback(err, data) { + console.info('==========================>getWantCallback=======================>'); + } + WantAgent.getWant(wantAgent, getWantCallback); +} +//WantAgentInfo对象 +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +``` + +## WantAgent.getWant + +getWant(agent: WantAgent): Promise\ + +获取WantAgent中的Want(Promise形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------------- | ---- | ------------- | +| agent | [WantAgent](js-apis-wantAgent.md) | 是 | WantAgent信息。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | 以Promise形式返回Want。 | + +**示例:** + +```ts +import WantAgent from '@ohos.wantAgent'; + + +//wantAgent对象 +let wantAgent; + +//WantAgentInfo对象 +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + wantAgent = data; + if (wantAgent) { + WantAgent.getWant(wantAgent).then((data) => { + console.info('==========================>getWantCallback=======================>'); + }); + } +}); +``` + ## WantAgent.getWantAgent getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void @@ -786,135 +925,6 @@ WantAgent.equal(wantAgent1, wantAgent2).then((data) => { }); ``` -## WantAgent.getOperationType9+ - -getOperationType(agent: WantAgent, callback: AsyncCallback\): void; - -获取一个WantAgent的OperationType信息(callback形式)。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------ | ---- | --------------------------------------- | -| agent | WantAgent | 是 | WantAgent对象。 | -| callback | AsyncCallback\ | 是 | 获取一个WantAgent的OperationType信息的回调方法。 | - -**示例:** - -```ts -import WantAgent from '@ohos.wantAgent'; - -//wantAgent对象 -let wantAgent; - -//WantAgentInfo对象 -let wantAgentInfo = { - wants: [ - { - deviceId: 'deviceId', - bundleName: 'com.neu.setResultOnAbilityResultTest1', - abilityName: 'com.example.test.EntryAbility', - action: 'action1', - entities: ['entity1'], - type: 'MIMETYPE', - uri: 'key={true,true,false}', - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: '[1, 2, 3]', - mykey3: 'ssssssssssssssssssssssssss', - mykey4: [false, true, false], - mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info('==========================>getWantAgentCallback=======================>'); - wantAgent = data; - if (data) { - WantAgent.getOperationType(wantAgent, (OperationType) => { - console.log('----------- getOperationType ----------, OperationType: ' + OperationType); - }) - } -}); -``` - -## WantAgent.getOperationType9+ - -getOperationType(agent: WantAgent): Promise\; - -获取一个WantAgent的OperationType信息(Promise形式)。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | --------- | ---- | ------------- | -| agent | WantAgent | 是 | WantAgent对象。 | - -**返回值:** - -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取operationType的结果。 | - -**示例:** - -```ts -import WantAgent from '@ohos.wantAgent'; - -//wantAgent对象 -let wantAgent; - -//WantAgentInfo对象 -let wantAgentInfo = { - wants: [ - { - deviceId: 'deviceId', - bundleName: 'com.neu.setResultOnAbilityResultTest1', - abilityName: 'com.example.test.EntryAbility', - action: 'action1', - entities: ['entity1'], - type: 'MIMETYPE', - uri: 'key={true,true,false}', - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: '[1, 2, 3]', - mykey3: 'ssssssssssssssssssssssssss', - mykey4: [false, true, false], - mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info('==========================>getWantAgentCallback=======================>'); - wantAgent = data; - WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); - }).catch((err) => { - console.log('getOperationType fail, err: ' + err); - }) -}); -``` - ## WantAgentFlags **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md index bb4cff3e2293e3d89c9ec53f1367f41d51b18104..9853827f5e3a37af24b76d19c8c0e982dfcc5b93 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md @@ -64,7 +64,7 @@ ws.connect(defaultIpAddress, (err, value) => { ## webSocket.createWebSocket -createWebSocket\(\): WebSocket +createWebSocket(): WebSocket 创建一个WebSocket,里面包括建立连接、关闭连接、发送数据和订阅/取消订阅WebSocket连接的打开事件、接收到服务器消息事件、关闭事件和错误事件。 @@ -89,7 +89,7 @@ let ws = webSocket.createWebSocket(); ### connect -connect\(url: string, callback: AsyncCallback\): void +connect(url: string, callback: AsyncCallback\): void 根据URL地址,建立一个WebSocket连接,使用callback方式作为异步方法。 @@ -128,7 +128,7 @@ ws.connect(url, (err, value) => { ### connect -connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void +connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void 根据URL地址和header,建立一个WebSocket连接,使用callback方式作为异步方法。 @@ -173,7 +173,7 @@ ws.connect(url, { ### connect -connect\(url: string, options?: WebSocketRequestOptions\): Promise +connect(url: string, options?: WebSocketRequestOptions): Promise\ 根据URL地址和header,建立一个WebSocket连接,使用Promise方式作为异步方法。 @@ -217,7 +217,7 @@ promise.then((value) => { ### send -send\(data: string | ArrayBuffer, callback: AsyncCallback\): void +send(data: string | ArrayBuffer, callback: AsyncCallback\): void 通过WebSocket连接发送数据,使用callback方式作为异步方法。 @@ -229,7 +229,7 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------ | -| data | string \| ArrayBuffer 8+ | 是 | 发送的数据。 | +| data | string \| ArrayBuffer | 是 | 发送的数据。
API 6及更早版本仅支持string类型。API 8起同时支持string和ArrayBuffer类型。 | | callback | AsyncCallback\ | 是 | 回调函数。 | **错误码:** @@ -258,7 +258,7 @@ ws.connect(url, (err, value) => { ### send -send\(data: string | ArrayBuffer\): Promise +send(data: string | ArrayBuffer): Promise\ 通过WebSocket连接发送数据,使用Promise方式作为异步方法。 @@ -270,7 +270,7 @@ send\(data: string | ArrayBuffer\): Promise | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------ | -| data | string \| ArrayBuffer 8+ | 是 | 发送的数据。 | +| data | string \| ArrayBuffer | 是 | 发送的数据。
API 6及更早版本仅支持string类型。API 8起同时支持string和ArrayBuffer类型。 | **返回值:** @@ -303,7 +303,7 @@ ws.connect(url, (err, value) => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 关闭WebSocket连接,使用callback方式作为异步方法。 @@ -341,7 +341,7 @@ ws.close((err, value) => { ### close -close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void +close(options: WebSocketCloseOptions, callback: AsyncCallback\): void 根据可选参数code和reason,关闭WebSocket连接,使用callback方式作为异步方法。 @@ -383,7 +383,7 @@ ws.close({ ### close -close\(options?: WebSocketCloseOptions\): Promise +close(options?: WebSocketCloseOptions): Promise\ 根据可选参数code和reason,关闭WebSocket连接,使用Promise方式作为异步方法。 @@ -427,9 +427,9 @@ promise.then((value) => { ``` -### on\('open'\) +### on('open') -on\(type: 'open', callback: AsyncCallback\): void +on(type: 'open', callback: AsyncCallback\): void 订阅WebSocket的打开事件,使用callback方式作为异步方法。 @@ -453,13 +453,13 @@ ws.on('open', (err, value) => { ``` -### off\('open'\) +### off('open') -off\(type: 'open', callback?: AsyncCallback\): void +off(type: 'open', callback?: AsyncCallback\): void 取消订阅WebSocket的打开事件,使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -484,14 +484,14 @@ ws.off('open', callback1); ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: AsyncCallback\): void +on(type: 'message', callback: AsyncCallback\): void 订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 ->![](public_sys-resources/icon-note.gif) **说明:** ->AsyncCallback中的数据可以是字符串\(API 6\)或ArrayBuffer\(API 8\)。 +>**说明:** +>AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 **系统能力**:SystemCapability.Communication.NetStack @@ -512,14 +512,14 @@ ws.on('message', (err, value) => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: AsyncCallback\): void +off(type: 'message', callback?: AsyncCallback\): void 取消订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 ->![](public_sys-resources/icon-note.gif) **说明:** ->AsyncCallback中的数据可以是字符串\(API 6\)或ArrayBuffer\(API 8\)。 +>**说明:** +>AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -539,9 +539,9 @@ ws.off('message'); ``` -### on\('close'\) +### on('close') -on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void +on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void 订阅WebSocket的关闭事件,使用callback方式作为异步方法。 @@ -552,7 +552,7 @@ on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 'close':WebSocket的关闭事件。 | -| callback | AsyncCallback<{ code: number, reason: string }> | 是 | 回调函数。 | +| callback | AsyncCallback\<{ code: number, reason: string }\> | 是 | 回调函数。
close:close错误码,reason:错误码说明 | **示例:** @@ -564,13 +564,13 @@ ws.on('close', (err, value) => { ``` -### off\('close'\) +### off('close') -off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void +off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void 取消订阅WebSocket的关闭事件,使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -580,7 +580,7 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 'close':WebSocket的关闭事件。 | -| callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 | +| callback | AsyncCallback\<{ code: number, reason: string }\> | 否 | 回调函数。
close:close错误码,reason:错误码说明 | **示例:** @@ -590,9 +590,9 @@ ws.off('close'); ``` -### on\('error'\) +### on('error') -on\(type: 'error', callback: ErrorCallback\): void +on(type: 'error', callback: ErrorCallback): void 订阅WebSocket的Error事件,使用callback方式作为异步方法。 @@ -615,13 +615,13 @@ ws.on('error', (err) => { ``` -### off\('error'\) +### off('error') -off\(type: 'error', callback?: ErrorCallback\): void +off(type: 'error', callback?: ErrorCallback): void 取消订阅WebSocket的Error事件,使用callback方式作为异步方法。 ->![](public_sys-resources/icon-note.gif) **说明:** +>**说明:** >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -645,7 +645,7 @@ ws.off('error'); 建立WebSocket连接时,可选参数的类型和说明。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -656,7 +656,7 @@ ws.off('error'); 关闭WebSocket连接时,可选参数的类型和说明。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -667,7 +667,7 @@ ws.off('error'); 发送给服务端的错误码可以自行定义,下面的列表仅供参考。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 值 | 说明 | | :-------- | :----------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-webview.md b/zh-cn/application-dev/reference/apis/js-apis-webview.md index d59bab84d8990988055fb4975eb010a084c8c05a..8a20506c9c19f6569ddeaabcb311fe51ab7aa93f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -2,7 +2,7 @@ # @ohos.web.webview (Webview) -提供web控制能力。 +@ohos.web.webview提供web控制能力,[web](../arkui-ts/ts-basic-components-web.md)组件提供具有网页显示能力。 > **说明:** > @@ -245,7 +245,7 @@ export default class EntryAbility extends UIAbility { } ``` -### setHttpDns +### setHttpDns10+ static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void @@ -3572,7 +3572,7 @@ struct Index { } ``` -### setAudioMuted +### setAudioMuted10+ setAudioMuted(mute: boolean): void @@ -3586,6 +3586,14 @@ setAudioMuted(mute: boolean): void | -------- | ------- | ---- | -------------------------------------- | | mute | boolean | 是 | 表示是否将网页设置为静音状态,true表示设置为静音状态,false表示取消静音状态。 | +**错误码:** + +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + **示例:** ```ts @@ -3626,7 +3634,7 @@ static getCookie(url: string): string | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | :------------------------ | -| url | string | 是 | 要获取的cookie所属的url。 | +| url | string | 是 | 要获取的cookie所属的url,建议使用完整的url。 | **返回值:** @@ -3682,7 +3690,7 @@ static setCookie(url: string, value: string): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | :------------------------ | -| url | string | 是 | 要设置的cookie所属的url。 | +| url | string | 是 | 要设置的cookie所属的url,建议使用完整的url。 | | value | string | 是 | 要设置的cookie的值。 | **错误码:** @@ -5212,7 +5220,7 @@ struct WebComponent { | isSupportCORS | boolean | 是 | 是 | 是否支持跨域请求。 | | isSupportFetch | boolean | 是 | 是 | 是否支持fetch请求。 | -## SecureDnsMode +## SecureDnsMode10+ Web組件使用HTTPDNS的模式。 @@ -5221,5 +5229,5 @@ Web組件使用HTTPDNS的模式。 | 名称 | 值 | 说明 | | ------------- | -- |----------------------------------------- | | Off | 0 |不使用HTTPDNS, 可以用于撤销之前使用的HTTPDNS配置。| -| Automatic | 1 |自动模式,用于解析的设定dns服务器不可用时,可自动回落至built-in DNS及系统DNS。| +| Auto | 1 |自动模式,用于解析的设定dns服务器不可用时,可自动回落至系统DNS。| | SecureOnly | 2 |强制使用设定的HTTPDNS服务器进行域名解析。| \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md index 31c3a192e7d0bc5449d9b4984546987f75b60a5e..241776a9120c3c76f25f800a1738db8399034e3b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md @@ -408,6 +408,8 @@ IP配置信息。 | caCertAliases | string | 是 | 否 | CA 证书别名。 | | caPath | string | 是 | 否 | CA 证书路径。 | | clientCertAliases | string | 是 | 否 | 客户端证书别名。 | +| certEntry | Uint8Array | 是 | 是 | CA 证书内容。 | +| certPassword | string | 是 | 是 | CA证书密码。 | | altSubjectMatch | string | 是 | 否 | 替代主题匹配。 | | domainSuffixMatch | string | 是 | 否 | 域后缀匹配。 | | realm | string | 是 | 否 | 通行证凭证的领域。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md index 6b973ac78d449daa3d32e2a7c28da46a5115202e..c20d64f6b5b7c381db039126c9dc01fb74e4e856 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -12,9 +12,9 @@ import wifiManagerExt from '@ohos.wifiManagerExt'; ``` -## wifiext.enableHotspot +## wifiext.enableHotspot9+ -enableHotspot(): boolean; +enableHotspot(): void; 使能WLAN热点。 @@ -30,9 +30,9 @@ enableHotspot(): boolean; | -------- | -------- | | 2701000 | Operation failed.| -## wifiext.disableHotspot +## wifiext.disableHotspot9+ -disableHotspot(): boolean; +disableHotspot(): void; 去使能WLAN热点。 @@ -48,9 +48,9 @@ disableHotspot(): boolean; | -------- | -------- | | 2701000 | Operation failed.| -## wifiext.getSupportedPowerModel +## wifiext.getSupportedPowerMode9+ -getSupportedPowerModel(): Promise<Array<PowerModel>> +getSupportedPowerMode(): Promise<Array<PowerMode>> 获取支持的功率模式,使用Promise异步回调。 @@ -62,7 +62,7 @@ getSupportedPowerModel(): Promise<Array<PowerModel>> | 类型 | 说明 | | -------- | -------- | - | Promise<Array<[PowerModel](#powermodel)>> | Promise对象。表示功率模式。 | + | Promise<Array<[PowerMode](#powermode)>> | Promise对象。表示功率模式。 | **错误码:** @@ -72,7 +72,7 @@ getSupportedPowerModel(): Promise<Array<PowerModel>> | -------- | -------- | | 2701000 | Operation failed.| -## PowerModel +## PowerMode 表示功率模式的枚举。 @@ -85,9 +85,9 @@ getSupportedPowerModel(): Promise<Array<PowerModel>> | THROUGH_WALL | 2 | 穿墙模式。 | -## wifiext.getSupportedPowerModel +## wifiext.getSupportedPowerMode9+ -getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void +getSupportedPowerMode(callback: AsyncCallback<Array<PowerMode>>): void 获取支持的功率模式,使用callback异步回调。 @@ -99,7 +99,7 @@ getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | 是 | 回调函数。当操作成功时,err为0,data表示支持的功率模式。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<Array<[PowerMode](#powermode)>> | 是 | 回调函数。当操作成功时,err为0,data表示支持的功率模式。如果error为非0,表示处理出现错误。 | **错误码:** @@ -109,9 +109,9 @@ getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): | -------- | -------- | | 2701000 | Operation failed.| -## wifiext.getPowerModel +## wifiext.getPowerMode9+ -getPowerModel(): Promise<PowerModel> +getPowerMode(): Promise<PowerMode> 获取功率模式,使用Promise异步回调。 @@ -123,7 +123,7 @@ getPowerModel(): Promise<PowerModel> | 类型 | 说明 | | -------- | -------- | - | Promise<[PowerModel](#powermodel)> | Promise对象。表示功率模式。 | + | Promise<[PowerMode](#powermode)> | Promise对象。表示功率模式。 | **错误码:** @@ -133,9 +133,9 @@ getPowerModel(): Promise<PowerModel> | -------- | -------- | | 2701000 | Operation failed.| -## wifiext.getPowerModel +## wifiext.getPowerMode9+ -getPowerModel(callback: AsyncCallback<PowerModel>): void +getPowerMode(callback: AsyncCallback<PowerMode>): void 获取功率模式,使用callback异步回调。 @@ -147,7 +147,7 @@ getPowerModel(callback: AsyncCallback<PowerModel>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | 是 | 回调函数。当操作成功时,err为0,data表示功率模式。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[PowerMode](#powermode)> | 是 | 回调函数。当操作成功时,err为0,data表示功率模式。如果error为非0,表示处理出现错误。 | **错误码:** @@ -157,9 +157,9 @@ getPowerModel(callback: AsyncCallback<PowerModel>): void | -------- | -------- | | 2701000 | Operation failed.| -## wifiext.setPowerModel +## wifiext.setPowerMode9+ -setPowerModel(model: PowerModel) : boolean; +setPowerMode(model: PowerMode) : boolean; 设置功率模式。 @@ -171,7 +171,7 @@ setPowerModel(model: PowerModel) : boolean; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | model | [PowerModel](#powermodel) | 是 | 功率模式。 | + | model | [PowerMode](#powermode) | 是 | 功率模式。 | **错误码:** 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 c7255c1a11c04fe1b5a32359acbe2c45a7e3564a..fafc82ba358585d0bca4198176f536a778caeefb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -40,7 +40,7 @@ import window from '@ohos.window'; | TYPE_LAUNCHER_DOCK9+ | 12 | 表示桌面Dock栏。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | | TYPE_VOICE_INTERACTION9+ | 13 | 表示智慧语音。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | | TYPE_POINTER9+ | 14 | 表示鼠标。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | -| TYPE_FLOAT_CAMERA9+ | 15 | 表示相机类型悬浮窗。
**模型约束:** 此接口仅可在Stage模型下使用。
**需要权限:** ohos.permission.SYSTEM_FLOAT_WINDOW | +| TYPE_FLOAT_CAMERA9+ | 15 | 表示相机类型悬浮窗。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | | TYPE_DIALOG9+ | 16 | 表示模态窗口。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | | TYPE_SCREENSHOT9+ | 17 | 表示截屏窗口。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统接口:** 此接口为系统接口。 | diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-tab-content.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-tab-content.md index 1d80f62b21b550d043a24153720a5e9da190dc4d..0ab16c7bdb3d8de0d215e19c8b1b596ea7c51019 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-tab-content.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-tab-content.md @@ -3,7 +3,7 @@ > **说明:** > 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -<[tabs](../arkui-js/js-components-container-tabs.md)>的子组件,用来展示tab的内容区,高度默认充满tabs剩余空间,子组件排列方式为横向排列,当作为容器组件的子元素时在主轴方向需要设置tab-content的确定长度,否则无法显示。 +<[tabs](../arkui-js/js-components-container-tabs.md)>的子组件,用来展示tab的内容区,高度默认充满tabs剩余空间,子组件排列方式为横向排列,当作为容器组件的子元素时在主轴方向需要设置tab-content的确定长度,否则无法显示。tab-content组件不支持内容过长时页面的滑动,如需页面滑动,可嵌套List使用。 ## 权限列表 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md index bbd00b8c1bf389bc026f2f3617fc3cc70e93cdd4..18cf415472a1b896c485b35bea6dfe5fe0583695 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md @@ -3,7 +3,7 @@ 自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,从而提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法如下: ```html - +
@@ -12,8 +12,8 @@ 结合if-else使用自定义组件的示例,showComp1为true时显示自定义组件comp1,否则显示comp2: ```html - - + +
@@ -76,7 +76,7 @@ export default { ```html - +
@@ -125,7 +125,7 @@ export default { ```html - +
父组件:{{text}} diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md index a384d0cce0f98cbb715089815d29acc5285db440..882d732f5a7e097dcfb573c49b67101a85f2dfcd 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md @@ -21,7 +21,7 @@ export default { ```html - +
@@ -57,7 +57,7 @@ export default { ```html - +
diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md index f5bceca1a24068409268c4e600872f24afafcba3..b3d541c6c8473b6a6da0d74348f0f98d97ef39cc 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md @@ -20,7 +20,7 @@ 引用该自定义组件方式如下: ```html - +
父组件中定义的内容 @@ -45,7 +45,7 @@ 引用该自定义组件方式如下: ```html - +
插入第二个插槽中 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 8b4292e8592f2ba22382ebf488ec8dd9e1c263e9..536201bfe0805ff55544d1c84de0fe137e7fcff7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -28,7 +28,6 @@ - [图形变换](ts-universal-attributes-transformation.md) - [图像效果](ts-universal-attributes-image-effect.md) - [形状裁剪](ts-universal-attributes-sharp-clipping.md) - - [文本样式设置](ts-universal-attributes-text-style.md) - [栅格设置](ts-universal-attributes-grid.md) - [颜色渐变](ts-universal-attributes-gradient-color.md) - [Popup控制](ts-universal-attributes-popup.md) @@ -43,6 +42,7 @@ - [背景模糊设置](ts-universal-attributes-backgroundBlurStyle.md) - [分布式迁移标识](ts-universal-attributes-restoreId.md) - [前景色设置](ts-universal-attributes-foreground-color.md) + - [文本通用属性](ts-universal-attributes-text-style.md) - 手势处理 - [绑定手势方法](ts-gesture-settings.md) - 基础手势 @@ -54,6 +54,7 @@ - [SwipeGesture](ts-basic-gestures-swipegesture.md) - [组合手势](ts-combined-gestures.md) - 基础组件 + - [AlphabetIndexer](ts-container-alphabet-indexer.md) - [Blank](ts-basic-components-blank.md) - [Button](ts-basic-components-button.md) - [Checkbox](ts-basic-components-checkbox.md) @@ -100,7 +101,6 @@ - [XComponent](ts-basic-components-xcomponent.md) - 容器组件 - [AbilityComponent](ts-container-ability-component.md) - - [AlphabetIndexer](ts-container-alphabet-indexer.md) - [Badge](ts-container-badge.md) - [Column](ts-container-column.md) - [ColumnSplit](ts-container-columnsplit.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animation.PNG b/zh-cn/application-dev/reference/arkui-ts/figures/animation.PNG deleted file mode 100644 index 92f92e0001a90840d03ebd00e0b0ef736c2a94c8..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/animation.PNG and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animation.gif b/zh-cn/application-dev/reference/arkui-ts/figures/animation.gif index 6cfbc07fc5122be3ecd69e6b33b6f00c0f676a0f..e1f1e9d8eedba5f4d7e9895fe10c1028cb8e19bd 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/animation.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/animation.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animation1.PNG b/zh-cn/application-dev/reference/arkui-ts/figures/animation1.PNG deleted file mode 100644 index 98cc1fa8c0537071549fa8185fa14f7ad103e7f8..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/animation1.PNG and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animation1.gif b/zh-cn/application-dev/reference/arkui-ts/figures/animation1.gif new file mode 100644 index 0000000000000000000000000000000000000000..d4fae00973755cc243e1d48f10acf9ef4b24682e Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/animation1.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/richText.png b/zh-cn/application-dev/reference/arkui-ts/figures/richText.png index 1520a854a9baed9fcc4e50e989bbfb4e83acf487..5d9db6f68aab7954ae1ac31e51f0b1abff7ebd76 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/richText.png and b/zh-cn/application-dev/reference/arkui-ts/figures/richText.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174104400.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174104400.gif index ec293bafaf6cd7204ebb231c4eee7daa504b78c3..da442c6a4f02d281bafff3f9fde8a51c6ebbf932 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174104400.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174104400.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982707.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982707.gif deleted file mode 100644 index ac096bd0f149b02d46013420a9c323fe8aa5805a..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982707.gif and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif new file mode 100644 index 0000000000000000000000000000000000000000..738e50b17cf1c20514f17034ec08bba1cadf2893 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777774.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777774.png index 60f430b646b45a3e3b16a9bb024e4a14e48bf4d3..24edbed60b52947c5effbba951a6523582603f30 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777774.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777774.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777775.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777775.png index 60f430b646b45a3e3b16a9bb024e4a14e48bf4d3..24edbed60b52947c5effbba951a6523582603f30 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777775.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777775.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_background_blur_style.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_background_blur_style.png index e9a7b0e3baa6d48739c2a3cfbc7b5b46600f9c70..9bec842e6d41af8a815ab24ce0897a0b75c8b8c4 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_background_blur_style.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_background_blur_style.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md b/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md index adfe8558de0cf3cac1ec2cbe908c18c75a11f0ab..bbb5191e854d930d31603463d6ddfa9ec49a89be 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -6,20 +6,21 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 名称 | 参数类型 | 必填 | 描述 | | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ | -| duration | number | 否 | 设置动画时长。单位为毫秒,默认动画时长为1000毫秒。
默认值:1000 | +| duration | number | 否 | 设置动画时长。单位为毫秒,默认动画时长为1000毫秒。
默认值:1000
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
- 在ArkTS卡片上最大动画持续时间为1000毫秒,若超出则固定为1000毫秒。 | | tempo | number | 否 | 动画播放速度。数值越大,动画播放速度越快,数值越小,播放速度越慢
值为0时,表示不存在动画。
默认值:1 | -| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve9+ | 否 | 设置动画曲线。默认曲线为线性。
默认值:Curve.Linear | +| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve9+ | 否 | 设置动画曲线。默认曲线为线性。
默认值:Curve.Linear
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | delay | number | 否 | 设置动画延迟执行的时长。单位为毫秒,默认不延时播放。
默认值:0 | | iterations | number | 否 | 设置播放次数。默认播放一次,设置为-1时表示无限次播放。
默认值:1 | -| playMode | [PlayMode](ts-appendix-enums.md#playmode) | 否 | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal | -| onFinish | () => void | 否 | 状态回调,动画播放完成时触发。 | +| playMode | [PlayMode](ts-appendix-enums.md#playmode) | 否 | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onFinish | () => void | 否 | 状态回调,动画播放完成时触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 @@ -36,11 +37,11 @@ struct AttrAnimationExample { build() { Column() { - Button('change width and height') + Button('change size') .onClick(() => { if (this.flag) { - this.widthSize = 100 - this.heightSize = 50 + this.widthSize = 150 + this.heightSize = 60 } else { this.widthSize = 250 this.heightSize = 100 @@ -66,8 +67,8 @@ struct AttrAnimationExample { duration: 1200, curve: Curve.Friction, delay: 500, - iterations: -1, // 设置-1表示动画无限循环 - playMode: PlayMode.AlternateReverse + iterations: -1, // 设置-1表示动画无限循环 + playMode: PlayMode.Alternate }) }.width('100%').margin({ top: 20 }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md index 01bd2021d811cf64c04b249a092e45ba3c45a858..2526c1c5a986456530cf9c9f7da8af37756bfdce 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -2,6 +2,8 @@ ## Color +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 颜色名称 | 颜色值 | 颜色示意 | | ------------------------ | -------- | ------------------------------------------------------------ | | Black | 0x000000 | ![zh-cn_image_0000001219864153](figures/zh-cn_image_0000001219864153.png) | @@ -19,6 +21,8 @@ ## ImageFit +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | --------- | ------------------------------------------------------------ | | Contain | 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。 | @@ -30,6 +34,8 @@ ## BorderStyle +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ----------------------------------------------- | | Dotted | 显示为一系列圆点,圆点半径为borderWidth的一半。 | @@ -38,6 +44,8 @@ ## LineJoinStyle +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----- | -------------------- | | Bevel | 使用斜角连接路径段。 | @@ -46,6 +54,8 @@ ## TouchType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------------ | | Down | 手指按下时触发。 | @@ -55,6 +65,8 @@ ## MouseButton +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | ---------------- | | Left | 鼠标左键。 | @@ -66,6 +78,8 @@ ## MouseAction +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | -------------- | | Press | 鼠标按键按下。 | @@ -75,6 +89,8 @@ ## Curve +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------------------- | ------------------------------------------------------------ | | Linear | 表示动画从头到尾的速度都是相同的。 | @@ -93,6 +109,8 @@ ## AnimationStatus +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | ------------------ | | Initial | 动画初始状态。 | @@ -102,6 +120,8 @@ ## FillMode +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | --------- | ------------------------------------------------------------ | | None | 动画未执行时不会将任何样式应用于目标,动画播放完成之后恢复初始默认状态。 | @@ -111,6 +131,8 @@ ## PlayMode +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---------------- | ------------------------------------------------------------ | | Normal | 动画按正常播放。 | @@ -120,6 +142,8 @@ ## KeyType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---- | ---------- | | Down | 按键按下。 | @@ -127,6 +151,8 @@ ## KeySource +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------------------- | | Unknown | 输入设备类型未知。 | @@ -136,16 +162,18 @@ | 名称 | 描述 | | -------- | ---------------------- | -| Top | 竖直方向上边缘 | -| Center(deprecated) | 竖直方向居中位置
从API version 9开始废弃 | -| Bottom | 竖直方向下边缘 | +| Top | 竖直方向上边缘
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| Center(deprecated) | 竖直方向居中位置
从API version 9开始废弃 | +| Bottom | 竖直方向下边缘
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | Baseline(deprecated) | 交叉轴方向文本基线位置
从API version 9开始废弃 | -| Start | 水平方向起始位置 | -| Middle(deprecated) | 水平方向居中位置
从API version 9开始废弃 | -| End | 水平方向末尾位置 | +| Start | 水平方向起始位置
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| Middle(deprecated) | 水平方向居中位置
从API version 9开始废弃 | +| End | 水平方向末尾位置
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## Week +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | ---------------------- | | Mon | 星期一 | @@ -158,6 +186,8 @@ ## Direction +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---- | ---------------------- | | Ltr | 元素从左到右布局。 | @@ -166,6 +196,8 @@ ## BarState +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---- | -------------------------------- | | Off | 不显示。 | @@ -174,6 +206,8 @@ ## EdgeEffect +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------------------------------------------ | | Spring | 弹性物理动效,滑动到边缘后可以根据初始速度或通过触摸事件继续滑动一段距离,松手后回弹。 | @@ -182,6 +216,8 @@ ## Alignment +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | ---------------- | | TopStart | 顶部起始端。 | @@ -196,6 +232,8 @@ ## TransitionType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | -------------------------------------------------- | | All | 指定当前的Transition动效生效在组件的所有变化场景。 | @@ -204,6 +242,8 @@ ## RelateType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------------- | | FILL | 缩放当前子组件以填充满父组件 | @@ -211,6 +251,8 @@ ## Visibility +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | -------------------------------- | | Hidden | 隐藏,但参与布局进行占位。 | @@ -219,6 +261,8 @@ ## LineCapStyle +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | -------------------- | | Butt | 线条两端为平行线,不额外扩展。 | @@ -227,6 +271,8 @@ ## Axis +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---------- | ------------ | | Vertical | 方向为纵向。 | @@ -234,6 +280,8 @@ ## HorizontalAlign +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------ | | Start | 按照语言方向起始端对齐。 | @@ -242,6 +290,8 @@ ## FlexAlign +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------------ | ------------------------------------------------------------ | | Start | 元素在主轴方向首端对齐,第一个元素与行首对齐,同时后续的元素与前一个对齐。 | @@ -253,6 +303,8 @@ ## ItemAlign +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | ------------------------------------------------------------ | | Auto | 使用Flex容器中默认配置。 | @@ -264,6 +316,8 @@ ## FlexDirection +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------------- | ------------------------------ | | Row | 主轴与行方向一致作为布局模式。 | @@ -273,6 +327,8 @@ ## FlexWrap +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | ------------------------------------------------- | | NoWrap | Flex容器的元素单行/列布局,子项不允许超出容器。 | @@ -281,6 +337,8 @@ ## VerticalAlign +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------ | | Top | 顶部对齐。 | @@ -289,6 +347,8 @@ ## ImageRepeat +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------------------------- | | X | 只在水平轴上重复绘制图片。 | @@ -298,6 +358,8 @@ ## ImageSize +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 类型 | 描述 | | ------- | ------------------------------------------------------------ | | Cover | 默认值,保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。 | @@ -306,6 +368,8 @@ ## GradientDirection +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | ---------- | | Left | 从右向左。 | @@ -320,6 +384,8 @@ ## SharedTransitionEffectType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | ---------- | | Static | 目标页面元素的位置保持不变,可以配置透明度动画。目前,只有为重定向到目标页面而配置的静态效果才会生效。 | @@ -327,6 +393,8 @@ ## FontStyle +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ---------------- | | Normal | 标准的字体样式。 | @@ -334,6 +402,8 @@ ## FontWeight +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | -------------- | | Lighter | 字体较细。 | @@ -345,6 +415,8 @@ ## TextAlign +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | -------------- | | Start | 水平对齐首部。 | @@ -353,6 +425,8 @@ ## TextOverflow +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------------------------------------- | | Clip | 文本超长时进行裁剪显示。 | @@ -361,6 +435,8 @@ ## TextDecorationType +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | ------------------ | | Underline | 文字下划线修饰。 | @@ -370,6 +446,8 @@ ## TextCase +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | --------- | -------------------- | | Normal | 保持文本原有大小写。 | @@ -378,6 +456,8 @@ ## ResponseType8+ +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ---------- | -------------------------- | | LongPress | 通过长按触发菜单弹出。 | @@ -385,6 +465,8 @@ ## HoverEffect8+ +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | --------- | ---------------------------- | | Auto | 使用组件的系统默认悬浮效果。 | @@ -394,6 +476,8 @@ ## Placement8+ +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------------- | ------------------------------------------------------------ | | Left | 气泡提示位于组件左侧,与组件左侧中心对齐。 | @@ -411,6 +495,8 @@ ## CopyOptions9+ +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | -------------------- | | None | 不支持复制。 | @@ -419,9 +505,40 @@ ## HitTestMode9+ +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----------- | -------------------- | | Default | 自身节点和子节点都响应触摸事件的命中测试,但会阻止被该节点屏蔽的其他节点的命中测试。 | | Block | 自身节点响应触摸事件的命中测试,但阻止被该节点屏蔽的子节点和其他节点的命中测试。 | | Transparent | 自身节点和子节点响应触摸事件的命中测试,并允许对被该节点屏蔽的其他节点进行命中测试。 | | None | 自身节点不会响应触摸事件的命中测试,但子节点会对触摸事件进行命中测试。 | + +## BlurStyle9+ + +该接口支持在ArkTS卡片中使用。 + + | 名称 | 描述 | + | ------- | ---------- | + | Thin | 轻薄材质模糊。 | + | Regular | 普通厚度材质模糊。 | + | Thick | 厚材质模糊。 | + | BackgroundThin | 近距景深模糊。 | + | BackgroundRegular | 中距景深模糊。 | + | BackgroundThick | 远距景深模糊。 | + | BackgroundUltraThick | 超远距景深模糊。 | + +## ThemeColorMode10+ + + | 名称 | 描述 | + | ------- | ---------- | + | System | 跟随系统深浅色模式。 | + | Light | 固定使用浅色模式。 | + | Dark | 固定使用深色模式。 | + +## AdaptiveColor10+ + + | 名称 | 描述 | + | ------- | ----------- | + | Default | 不使用取色模糊。使用默认的颜色作为蒙版颜色。 | + | Average | 使用取色模糊。将取色区域的颜色平均值作为蒙版颜色。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 6d1d1b49596bbd1dc23c5852b8e471918e5d58cf..16bb9d5c487dc9b47ef9302ce1a3ad9d8942f85c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -16,6 +16,8 @@ Blank(min?: number | string) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,7 +30,7 @@ Blank(min?: number | string) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | 设置空白填充的填充颜色。 | +| color | [ResourceColor](ts-types.md#resourcecolor) | 设置空白填充的填充颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md index 3579acfe447e6c34457ea9337d0502357c9d5a43..edc5f3bab449b09998a8e9ec577deeac09d61a1d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -16,6 +16,8 @@ **方法1:** Button(options?: {type?: ButtonType, stateEffect?: boolean}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,6 +30,8 @@ 使用文本内容创建相应的按钮组件,此时Button无法包含子组件。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -40,10 +44,13 @@ | 名称 | 参数类型 | 描述 | | ----------- | ----------- | --------------------------------- | -| type | ButtonType | 设置Button样式。
默认值:ButtonType.Capsule | -| stateEffect | boolean | 按钮按下时是否开启按压态显示效果,当设置为false时,按压效果关闭。
默认值:true | +| type | ButtonType | 设置Button样式。
默认值:ButtonType.Capsule
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| stateEffect | boolean | 按钮按下时是否开启按压态显示效果,当设置为false时,按压效果关闭。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## ButtonType枚举说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | ------------------ | | Capsule | 胶囊型按钮(圆角默认为高度的一半)。 | @@ -51,8 +58,8 @@ | Normal | 普通按钮(默认不带圆角)。 | > **说明:** -> - 按钮圆角通过[通用属性borderRadius](ts-universal-attributes-border.md)设置(不支持通过border接口设置圆角),且只支持设置一个相同的圆角。 -> - 当按钮类型为Capsule时,borderRadius设置不生效,按钮圆角始终为高度的一半。 +> - 按钮圆角通过[通用属性borderRadius](ts-universal-attributes-border.md)设置(不支持通过border接口设置圆角),且只支持设置参数为[Length](ts-types.md#length)的圆角。 +> - 当按钮类型为Capsule时,borderRadius设置不生效,按钮圆角始终为宽、高中较小值的一半。 > - 当按钮类型为Circle时,borderRadius即为按钮半径,若未设置borderRadius按钮半径则为宽、高中较小值的一半。 > - 按钮文本通过[通用文本样式](ts-universal-attributes-text-style.md)进行设置。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index 9d1669047af57332bf85b5a6122bd183ed2b49e7..ab5f04d2981a6a063355d022a66eacd492011199 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -14,6 +14,8 @@ Checkbox(options?: {name?: string, group?: string }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,16 +30,16 @@ Checkbox(options?: {name?: string, group?: string }) | 名称 | 参数类型 | 描述 | | ------------- | ------- | -------- | -| select | boolean | 设置多选框是否选中。
默认值:false | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置多选框选中状态颜色。 | +| select | boolean | 设置多选框是否选中。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置多选框选中状态颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: -| 名称 | 功能描述 | -| ----------| -------- | -|onChange(callback: (value: boolean) => void) | 当选中状态发生变化时,触发该回调。(只有手动触发且Checkbox状态改变时才会触发onChange回调)
- value为true时,表示已选中。
- value为false时,表示未选中。 | +| 名称 | 功能描述 | +| -------------------------------------------- | ------------------------------------------------------------ | +| onChange(callback: (value: boolean) => void) | 当选中状态发生变化时,触发该回调。(只有手动触发且Checkbox状态改变时才会触发onChange回调)
- value为true时,表示已选中。
- value为false时,表示未选中。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index df19c5e7c4a4781734ad174552f239fe63219a81..70d75bc16fce4d7e7f7ef8a86082594e550cd062 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -16,9 +16,9 @@ CheckboxGroup(options?: { group?: string }) 创建多选框群组,可以控制群组内的Checkbox全选或者不全选,group值相同的Checkbox和CheckboxGroup为同一群组。 -**参数:** - +从API version 9开始,该接口支持在ArkTS卡片中使用。 +**参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | @@ -30,8 +30,8 @@ CheckboxGroup(options?: { group?: string }) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| selectAll | boolean | 设置是否全选。
默认值:false,若同组的Checkbox显式设置select,则Checkbox的优先级高。 | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置被选中或部分选中状态的颜色。 | +| selectAll | boolean | 设置是否全选。
默认值:false,若同组的Checkbox显式设置select,则Checkbox的优先级高。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置被选中或部分选中状态的颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 @@ -39,9 +39,12 @@ CheckboxGroup(options?: { group?: string }) | 名称 | 功能描述 | | -------- | -------- | -| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult对象说明)) => void ) |CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化时,触发回调。(只有手动触发且Checkbox或CheckboxGroup状态改变时才会触发onChange回调)| +| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult对象说明)) => void ) |CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化时,触发回调。(只有手动触发且Checkbox或CheckboxGroup状态改变时才会触发onChange回调)
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## CheckboxGroupResult对象说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 描述 | | ------ | ------ | ------- | | name | Array<string> | 群组内所有被选中的多选框名称。 | @@ -49,6 +52,8 @@ CheckboxGroup(options?: { group?: string }) ## SelectStatus枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ----- | -------------------- | | All | 群组多选择框全部选择。 | 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 655e9424a3eabbdabcd0fea188cd4f7ae1dce1ef..647e934cecd29e52ec55630de50f0310f01e267a 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 @@ -18,6 +18,8 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,6 +30,9 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) ## DataPanelType枚举说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------| ------------ | | Line | 线型数据面板。 | @@ -41,33 +46,40 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | -| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#LinearGradient对象说明)> | 是 | 各数据段颜色 ( ResourceColor为纯色,LinearGradient为渐变色)。| +| closeEffect | boolean | 是 | 关闭数据占比图表旋转动效。
默认值:false。| +| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | 是 | 各数据段颜色,ResourceColor为纯色,LinearGradient为渐变色。| | trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 是 | 底板颜色。| | strokeWidth10+ | [Length](ts-types.md#Length) | 是 | 圆环粗细。 | -| trackShadow10+ | [DataPanelShadowOption](#DataPanelShadowOption对象说明) | 是 | 投影样式,不设置为不开启投影。| +| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10) | 是 | 投影样式,不设置为不开启投影。| -## DataPanelShadowOption对象说明 +## DataPanelShadowOption10+ | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | -| radius10+ | number \| [Resource](ts-types.md#resource类型) | 否 | 阴影模糊半径。
默认值:5vp | -| colors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#LinearGradient对象说明)> | 否 | 各数据段阴影的颜色。
默认值:与valueColors一致 | -| offsetX10+ | number \| [Resource](ts-types.md#resource类型) | 否 | X轴的偏移量。
默认值:5vp | -| offsetY10+ | number \| [Resource](ts-types.md#resource类型) | 否 | Y轴的偏移量。
默认值:5vp | +| radius | number \| [Resource](ts-types.md#resource类型) | 否 | 阴影模糊半径。
默认值:5vp。 | +| colors | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | 否 | 各数据段阴影的颜色。
默认值:与valueColors值相同。 | +| offsetX | number \| [Resource](ts-types.md#resource类型) | 否 | X轴的偏移量。
默认值:5vp。 | +| offsetY | number \| [Resource](ts-types.md#resource类型) | 否 | Y轴的偏移量。
默认值:5vp。 | + +## LinearGradient10+ +线性渐变颜色描述。 -## LinearGradient对象说明 -线性渐变。 +LinearGradient(colorStops: ColorStop[]) -LinearGradient(colorStops: ColorStop[])10+ +| 名称 | 参数类型 | 必填 | 描述 | +| ------------- | ------- | ---- | -------- | +| colorStops | [ColorStop](#colorstop10)[] | 是 | 存储渐变颜色和渐变点。| -## ColorStop对象说明 +## ColorStop10+ + 颜色断点类型,用于描述渐进色颜色断点。 + | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | -| color10+ | [ResourceColor](ts-types.md#resourcecolor) | 是 | 颜色值。| -| offset10+ | [Length](ts-types.md#Length) | 是 | 渐变色断点(0~1之间的比例值)。| +| color | [ResourceColor](ts-types.md#resourcecolor) | 是 | 颜色值。| +| offset | [Length](ts-types.md#Length) | 是 | 渐变色断点(0~1之间的比例值)。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-divider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-divider.md index 46f2ac309214572ce06ddc33505ff882353ff43d..edac89e88e2d77fdc39d7a838df4fd666fce36d7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-divider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-divider.md @@ -16,21 +16,18 @@ Divider() +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: | 名称 | 参数类型 | 描述 | | ----------- | ---------- | ------------------ | -| vertical | boolean | 使用水平分割线还是垂直分割线。false:水平分割线;true:垂直分割线。
默认值:false | -| color | [ResourceColor](ts-types.md#resourcecolor) | 分割线颜色。 | -| strokeWidth | number \| string | 分割线宽度。
默认值:1 | -| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 分割线的端点样式。
默认值:LineCapStyle.Butt | - - -## 事件 - -不支持通用事件。 +| vertical | boolean | 使用水平分割线还是垂直分割线。false:水平分割线;true:垂直分割线。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| color | [ResourceColor](ts-types.md#resourcecolor) | 分割线颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeWidth | number \| string | 分割线宽度。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
分割线的宽度不支持百分比设置。 | +| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 分割线的端点样式。
默认值:LineCapStyle.Butt
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md index d451d3fd941f47c54577fc54125255a713e35ea7..c8737ca8a0712ae7f8025b17fa46c1f4762c38f4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md @@ -108,7 +108,7 @@ struct CardExample { .visibility(Visibility.Visible) .onAcquired((form)=>{ console.log(`form info : ${JSON.stringify(form)}`); - this.fomId = form.id; + this.formId = form.id; }) .onError((err)=>{ console.log(`fail to add form, err: ${JSON.stringify(err)}`); 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 16884200f16f3521dcd875a035f242050afb282a..8f2609ef6a4828d2703f7066e08036266a107ca9 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 @@ -17,6 +17,8 @@ Gauge(options:{value: number, min?: number, max?: number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -31,16 +33,18 @@ Gauge(options:{value: number, min?: number, max?: number}) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| value | number | 设置量规图的数据值,可用于动态修改量规图的数据值。
默认值:0 | -| startAngle | number | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:0 | -| endAngle | number | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:360 | -| colors | Array<[ColorStop](#colorstop)> | 设置量规图的颜色,支持分段颜色设置。 | -| strokeWidth | Length | 设置环形量规图的环形厚度。 | +| value | number | 设置量规图的数据值,可用于动态修改量规图的数据值。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| startAngle | number | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| endAngle | number | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:360
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| colors | Array<[ColorStop](#colorstop)> | 设置量规图的颜色,支持分段颜色设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeWidth | Length | 设置环形量规图的环形厚度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## ColorStop 颜色断点类型,用于描述渐进色颜色断点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型定义 | 描述 | | --------- | -------------------- | ------------------------------------------------------------ | | ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | 描述渐进色颜色断点类型,第一个参数为颜色值,若设置为非颜色类型,则置为黑色。第二个参数为颜色所占比重,若设置为负数或是非数值类型,则将比重置为0,该颜色不显示。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index c24c6392c9aed18c90c1a03806dc51ce7ceaa601..0492a368d84457e0fb99e7ed3be7257f1d27308e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -23,11 +23,13 @@ Image(src: string | PixelMap | Resource) 通过图片数据源获取图片,用于后续渲染展示。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource类型) | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持`datashare://`路径前缀的字符串,用于访问通过data ability提供的图片路径。图片加载前需要申请[媒体库功能相关权限](../../file-management/medialibrary-overview.md#申请媒体库功能相关权限)
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 | +| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource类型) | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持`datashare://`路径前缀的字符串,用于访问通过data ability提供的图片路径。图片加载前需要申请[媒体库功能相关权限](../../file-management/medialibrary-overview.md#申请媒体库功能相关权限)
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。
**说明:**
- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。
- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串
- ArkTS卡片上不支持 [PixelMap](../apis/js-apis-image.md#pixelmap7)类型 | ## 属性 @@ -35,20 +37,20 @@ Image(src: string | PixelMap | Resource) | 名称 | 参数类型 | 描述 | | --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | -| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。 | -| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover | -| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。
默认值:ImageRepeat.NoRepeat
**说明:**
svg类型图源不支持该属性。 | -| interpolation | [ImageInterpolation](#imageinterpolation) | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
默认值:ImageInterpolation.None
**说明:**
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | -| renderMode | [ImageRenderMode](#imagerendermode) | 设置图片渲染的模式。
默认值:ImageRenderMode.Original
**说明:**
svg类型图源不支持该属性。 | -| sourceSize | {
width: number,
height: number
} | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。
**说明:**
PixelMap资源和SVG图片不支持该属性。 | -| matchTextDirection | boolean | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false | -| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false | -| fillColor | [ResourceColor](ts-types.md#resourcecolor) | 填充颜色。设置的填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片的fill颜色。 | -| autoResize | boolean | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。
默认值:true | -| syncLoad8+ | boolean | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置图片是否可复制(SVG图片不支持复制)。
当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。
默认值:CopyOptions.None | -| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | 给图像设置颜色滤镜效果。 | -| draggable9+ | boolean | 设置默认拖拽效果。(不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。)
默认值:false | +| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。
默认值:ImageRepeat.NoRepeat
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | +| interpolation | [ImageInterpolation](#imageinterpolation) | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
默认值:ImageInterpolation.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | +| renderMode | [ImageRenderMode](#imagerendermode) | 设置图片渲染的模式。
默认值:ImageRenderMode.Original
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | +| sourceSize | {
width: number,
height: number
} | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
PixelMap资源和SVG图片不支持该属性。 | +| matchTextDirection | boolean | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillColor | [ResourceColor](ts-types.md#resourcecolor) | 填充颜色。设置的填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片的fill颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| autoResize | boolean | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| syncLoad8+ | boolean | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置图片是否可复制(SVG图片不支持复制)。
当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。
默认值:CopyOptions.None
该接口支持在ArkTS卡片中使用。 | +| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | 给图像设置颜色滤镜效果。
该接口支持在ArkTS卡片中使用。 | +| draggable9+ | boolean | 设置默认拖拽效果。(不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。)
默认值:false
该接口支持在ArkTS卡片中使用。 | > **说明:** > @@ -57,6 +59,8 @@ Image(src: string | PixelMap | Resource) ### ImageInterpolation +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------- | | None | 不使用插值图片数据。 | @@ -66,6 +70,8 @@ Image(src: string | PixelMap | Resource) ### ImageRenderMode +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | --------------------- | | Original | 按照原图进行渲染,包括颜色。 | @@ -77,9 +83,9 @@ Image(src: string | PixelMap | Resource) | 名称 | 功能描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
 componentHeight: number, loadingStatus: number }) => void) | 图片成功加载时触发该回调,返回成功加载的图片尺寸。
- width:图片的宽,单位为像素。
- height:图片的高,单位为像素。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。
- loadingStatus:图片加载成功的状态。
| -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | 图片加载出现异常时触发该回调。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。 | -| onFinish(event: () => void) | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。 | +| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
 componentHeight: number, loadingStatus: number }) => void) | 图片成功加载时触发该回调,返回成功加载的图片尺寸。
- width:图片的宽,单位为像素。
- height:图片的高,单位为像素。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。
- loadingStatus:图片加载成功的状态。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
loadingStatus返回的状态值为0时,代表图片加载失败;返回的状态值为1时,代表图片加载成功。 | +| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | 图片加载出现异常时触发该回调。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onFinish(event: () => void) | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 @@ -356,18 +362,14 @@ struct ImageExample3 { ```ts import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs'; -import context from '@ohos.app.ability.context'; +import context from '@ohos.app.ability.common'; @Entry @Component struct LoadImageExample { @State resourcesPath: string = '' @State sandboxPath: string = '' - context: context.AbilityContext - - aboutToAppear() { - this.context = getContext(this) as context.AbilityContext - } + context: context.UIAbility = getContext(this) as context.UIAbilityContext build() { Column() { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index d52eaf34dbfe8a77bebb67e3e18f43238e35644a..b75519c1419a2d30ec0b4c2ae34112f2ab73b502 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -18,11 +18,13 @@ LoadingProgress() 创建加载进展组件。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## 属性 | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | 设置加载进度条前景色。 | +| color | [ResourceColor](ts-types.md#resourcecolor) | 设置加载进度条前景色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index bb26b0a9af1b258a36a7ca6c5eef246fd8274740..bbf92272113f7c71bcfdeaeee4570e11947566cc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -17,29 +17,31 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | | start | boolean | 是 | 控制跑马灯是否进入播放状态。 | | step | number | 否 | 滚动动画文本滚动步长。
默认值:6,单位vp | -| loop | number | 否 | 设置重复滚动的次数,小于等于零时无限循环。
默认值:-1 | +| loop | number | 否 | 设置重复滚动的次数,小于等于零时无限循环。
默认值:-1
**说明:**
ArkTS卡片上该参数设置任意值都仅在可见时滚动一次。 | | fromStart | boolean | 否 | 设置文本从头开始滚动或反向滚动。
默认值:true | | src | string | 是 | 需要滚动的文本。 | ## 属性 -| 名称 | 参数类型 | 描述 | -| ---------- | -------- | ------------------------------------ | -| allowScale | boolean | 是否允许文本缩放。
默认值:false | +| 名称 | 参数类型 | 描述 | +| ---------- | -------- | ------------------------------------------------------------ | +| allowScale | boolean | 是否允许文本缩放。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 | 名称 | 功能描述 | | -------- | -------- | -| onStart(event: () => void) | 开始滚动时触发回调。 | -| onBounce(event: () => void) | 完成一次滚动时触发,若循环次数不为1,则该事件会多次触发。 | -| onFinish(event: () => void) | 滚动全部循环次数完成时触发回调。 | +| onStart(event: () => void) | 开始滚动时触发回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onBounce(event: () => void) | 完成一次滚动时触发,若循环次数不为1,则该事件会多次触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onFinish(event: () => void) | 滚动全部循环次数完成时触发回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md index 0bad69d7c539028e0e165cc3e16a27ca93575876..f4d92ad423e1a47497d5673b2ce8dea3a587f09d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md @@ -46,7 +46,7 @@ PluginComponent(value: { template: PluginComponentTemplate, data: KVObject}) ```ts //PluginUserExample.ets -import plugin from "plugin_component.js" +import plugin from "./plugin_component.js" @Entry @Component @@ -102,7 +102,7 @@ struct PluginUserExample { ```ts //PluginProviderExample.ets -import plugin from "plugin_component.js" +import plugin from "./plugin_component.js" @Entry @Component diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 85d343bdb5a1e405b2a30f966d1f3f5d2099ab55..69b6d182ffbf5d3bea4e4f47d6163c4ecf0109ca 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -18,17 +18,21 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) 创建进度组件,用于显示内容加载或操作处理进度。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 指定当前进度值。设置小于0的数值时置为0,设置大于total的数值时置为total。 | -| total | number | 否 | 指定进度总长。
默认值:100 | -| type8+ | [ProgressType](#progresstype枚举说明) | 否 | 指定进度条类型。
默认值:ProgressType.Linear | +| value | number | 是 | 指定当前进度值。设置小于0的数值时置为0,设置大于total的数值时置为total。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| total | number | 否 | 指定进度总长。
默认值:100
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| type8+ | [ProgressType](#progresstype枚举说明) | 否 | 指定进度条类型。
默认值:ProgressType.Linear
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | styledeprecated | [ProgressStyle](#progressstyle枚举说明) | 否 | 指定进度条样式。
该参数从API version8开始废弃,建议使用type替代。
默认值:ProgressStyle.Linear | ## ProgressType枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------- | | Linear | 线性样式。从API version9开始,高度大于宽度的时候自适应垂直显示。 | @@ -39,6 +43,8 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) ## ProgressStyle枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | --------- | ------------------------------------------------------------ | | Linear | 线性样式。 | @@ -51,10 +57,10 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| value | number | 设置当前进度值。设置小于0的数值时置为0,设置大于total的数值时置为total。非法数值不生效。 | -| color | [ResourceColor](ts-types.md#resourcecolor) | 设置进度条前景色。 | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置进度条底色。 | -| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | 定义组件的样式。
- strokeWidth: 设置进度条宽度(不支持百分比设置)。从API version9开始,环形进度条设置宽度大于等于半径时,默认修改宽度至半径值的二分之一。
默认值:4.0Vp
- scaleCount: 设置环形进度条总刻度数。
默认值:120
- scaleWidth: 设置环形进度条刻度粗细(不支持百分比设置),刻度粗细大于进度条宽度时,为系统默认粗细。
默认值:2.0Vp | +| value | number | 设置当前进度值。设置小于0的数值时置为0,设置大于total的数值时置为total。非法数值不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| color | [ResourceColor](ts-types.md#resourcecolor) | 设置进度条前景色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置进度条底色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | 定义组件的样式。
- strokeWidth: 设置进度条宽度(不支持百分比设置)。从API version9开始,环形进度条设置宽度大于等于半径时,默认修改宽度至半径值的二分之一。
默认值:4.0Vp
- scaleCount: 设置环形进度条总刻度数。
默认值:120
- scaleWidth: 设置环形进度条刻度粗细(不支持百分比设置),刻度粗细大于进度条宽度时,为系统默认粗细。
默认值:2.0Vp
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index 89ae82004a405e536ad3e7c686190a68528b43ba..e6e48f77ebd3b8d73f5a1a72997021cdcc2dd850 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -16,6 +16,8 @@ QRCode(value: string) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,13 +30,13 @@ QRCode(value: string) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | 设置二维码颜色。
默认值:Color.Black | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置二维码背景颜色。
默认值:Color.White | +| color | [ResourceColor](ts-types.md#resourcecolor) | 设置二维码颜色。
默认值:Color.Black
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置二维码背景颜色。
默认值:Color.White
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 事件 -通用事件仅支持[点击事件](ts-universal-events-click.md)。 +通用事件支持[点击事件](ts-universal-events-click.md)、[触摸事件](ts-universal-events-touch.md)、[挂载卸载事件](ts-universal-events-show-hide.md)。 ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-radio.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-radio.md index 76bc6a9a644384009be751b746e26b00df26f6c8..4a496bc9760dbaf909443ab5721d6bcc00bfd7d3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-radio.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-radio.md @@ -16,6 +16,8 @@ Radio(options: {value: string, group: string}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -29,7 +31,7 @@ Radio(options: {value: string, group: string}) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| checked | boolean | 设置单选框的选中状态。
默认值:false | +| checked | boolean | 设置单选框的选中状态。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 事件 @@ -37,7 +39,7 @@ Radio(options: {value: string, group: string}) | 名称 | 功能描述 | | -------- | -------- | -| onChange(callback: (isChecked: boolean) => void) | 单选框选中状态改变时触发回调。
-isChecked为true时,代表选中。
-isChecked为false时,代表未选中。 | +| onChange(callback: (isChecked: boolean) => void) | 单选框选中状态改变时触发回调。
-isChecked为true时,代表选中。
-isChecked为false时,代表未选中。
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md index 458692f9d232176521f0c46d7510abc907ebb9f0..4eb14ade0656357c208feff8d0cd7e0b9d8a0f6b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -16,6 +16,8 @@ Rating(options?: { rating: number, indicator?: boolean }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,16 +30,16 @@ Rating(options?: { rating: number, indicator?: boolean }) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| stars | number | 设置评星总数。
默认值:5 | -| stepSize | number | 操作评级的步长。
默认值:0.5 | -| starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | backgroundUri:未选中的星级的图片链接,可由用户自定义或使用系统默认图片,仅支持本地图片。
foregroundUri:选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地图片。
secondaryUir:部分选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地图片。 | +| stars | number | 设置评星总数。
默认值:5
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| stepSize | number | 操作评级的步长。
默认值:0.5
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | backgroundUri:未选中的星级的图片链接,可由用户自定义或使用系统默认图片。
foregroundUri:选中的星级的图片路径,可由用户自定义或使用系统默认图片。
secondaryUir:部分选中的星级的图片路径,可由用户自定义或使用系统默认图片。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
startStyle属性所支持的图片类型能力参考[Image](ts-basic-components-image.md)组件。
支持加载本地图片和网络图片,暂不支持PixelMap类型和Resource资源。
默认图片加载方式为异步,暂不支持同步加载。 | ## 事件 | 名称 | 功能描述 | | -------- | -------- | -| onChange(callback:(value: number) => void) | 操作评分条的评星发生改变时触发该回调。 | +| onChange(callback:(value: number) => void) | 操作评分条的评星发生改变时触发该回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 37311ca3d0420a53c2e41b0f635fdc7eb9c11fd5..77185a29a95553779eb45351b086d1944d53e95f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -31,6 +31,10 @@ RichText(content:string) | onStart(callback: () => void) | 加载网页时触发。 | | onComplete(callback: () => void) | 网页加载结束时触发。 | +## 属性 + +只支持[通用属性](ts-universal-attributes-size.md)中width,height,size,layoutWeight四个属性。由于padding,margin,constraintSize属性使用时与通用属性描述不符,暂不支持。 + ## 支持标签 | 名称 | 描述 | 示例 | @@ -46,7 +50,7 @@ RichText(content:string) | \\ | 定义与常规文本风格不同的文本,像拼写错误的单词或者汉语中的专有名词,应尽量避免使用\为文本加下划线,用户会把它混淆为一个超链接。 | \

\这是带有下划线的段落\\

| | \ | 定义HTML文档的样式信息。 | \ | | style | 属性规定元素的行内样式,写在标签内部,在使用的时候需用引号来进行区分,并以; 间隔样式,style='width: 500px;height: 500px;border: 1px soild;margin: 0 auto;'。 | \

这是一个标题\

\

这是一个段落。\

| -| \ | 用于定义客户端文本,比如JavaScript。 | \ | +| \ | 用于定义客户端脚本,比如JavaScript。 | \ | ## 示例 @@ -78,6 +82,29 @@ struct RichTextExample { .onComplete(() => { console.info('RichText onComplete'); }) + .width(500) + .height(400) + .backgroundColor(0XBDDB69) + RichText('layoutWeight(1)') + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) + .size({ width: '100%', height: 110 }) + .backgroundColor(0X92D6CC) + .layoutWeight(1) + RichText('layoutWeight(2)') + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) + .size({ width: '100%', height: 110 }) + .backgroundColor(0X92C48D) + .layoutWeight(2) } } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md index c8d7d5482648345ceedf04c6b5036ed2b6655e6d..77c048608660ee281b52a263848f838b97d2379f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -16,6 +16,8 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, style?: SliderStyle, direction?: Axis, reverse?: boolean}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -30,6 +32,8 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty ## SliderStyle枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------- | | OutSet | 滑块在滑轨上。 | @@ -42,12 +46,12 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| blockColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块的颜色。 | -| trackColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的背景颜色。 | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的已滑动部分颜色。 | -| showSteps | boolean | 设置当前是否显示步长刻度值。
默认值:false | -| showTips | boolean | 设置滑动时是否显示百分比气泡提示。
默认值:false | -| trackThickness | [Length](ts-types.md#length) | 设置滑轨的粗细。 | +| blockColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块的颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| trackColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的背景颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的已滑动部分颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| showSteps | boolean | 设置当前是否显示步长刻度值。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| showTips | boolean | 设置滑动时是否显示百分比气泡提示。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
当direction的属性值为Axis.Horizontal时,tip显示在滑块正上方。值为Axis.Vertical时,tip显示在滑块正左边。
tip的绘制区域为Slider自身节点的overlay。
Slider不设置边距,或者边距比较小时,tip会被截断。 | +| trackThickness | [Length](ts-types.md#length) | 设置滑轨的粗细。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 @@ -56,15 +60,17 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | 名称 | 功能描述 | | -------- | -------- | -| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Slider滑动时触发事件回调。
value:当前滑动进度值。若返回值有小数,可使用Math.toFixed()方法将数据处理为预期的精度。
mode:拖动状态。 | +| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Slider拖到或点击时触发事件回调。
value:当前滑动进度值。若返回值有小数,可使用Math.toFixed()方法将数据处理为预期的精度。
mode:事件触发的相关状态值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Begin和End状态当手势点击时都会触发,Moving和Click状态当value值发生变换时触发。
当连贯动作为拖动动作时,不触发Click状态。
value值的变化范围为对应步长steps数组。 | ## SliderChangeMode枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 值 | 描述 | | -------- | -------- | -------- | -| Begin | 0 | 开始拖动滑块。 | +| Begin | 0 | 手势/鼠标接触或者按下滑块。 | | Moving | 1 | 正在拖动滑块过程中。 | -| End | 2 | 结束拖动滑块。 | +| End | 2 | 手势/鼠标离开滑块。 | | Click | 3 | 点击滑动条使滑块位置移动。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-span.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-span.md index 5e615e7033fbe11e87ff2746df9547684a56f2d9..ebe015253108955d4c0e4f8ad029367a42da08f3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -16,6 +16,8 @@ Span(value: string | Resource) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -29,9 +31,9 @@ Span(value: string | Resource) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None
color:Color.Black
} | -| letterSpacing | number \| string | 设置文本字符间距。取值小于0,字符聚集重叠,取值大于0且随着数值变大,字符间距越来越大,稀疏分布。 | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。
默认值:TextCase.Normal | +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| letterSpacing | number \| string | 设置文本字符间距。取值小于0,字符聚集重叠,取值大于0且随着数值变大,字符间距越来越大,稀疏分布。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。
默认值:TextCase.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md index 5431ce7579ab88a9d4972bd4fde5c47b5ae5179d..9392eef756b9c5eb3baace5dadb64b84ff4b21cc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -16,6 +16,8 @@ Text(content?: string | Resource) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,17 +30,17 @@ Text(content?: string | Resource) | 名称 | 参数类型 | 描述 | | ----------------------- | ----------------------------------- | ------------------------------------------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式
默认值:TextAlign.Start
说明:
文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置。 | -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
需配合`maxLines`使用,单独设置不生效。 | -| maxLines | number | 设置文本的最大行数。
默认值:Infinity
**说明:**
默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。 | -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 | -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
} | -| baselineOffset | number \| string | 设置文本基线的偏移量,默认值0。 | -| letterSpacing | number \| string | 设置文本字符间距。 | -| minFontSize | number \| string \| [Resource](ts-types.md#resource) | 设置文本最小显示字号。
需配合maxFontSize以及maxline或布局大小限制使用,单独设置不生效。 | -| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | 设置文本最大显示字号。
需配合minFontSize以及maxline或布局大小限制使用,单独设置不生效。 | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。
默认值:TextCase.Normal | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 组件支持设置文本是否可复制粘贴。
默认值:CopyOptions.None | +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式
默认值:TextAlign.Start
说明:
文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
需配合`maxLines`使用,单独设置不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| maxLines | number | 设置文本的最大行数。
默认值:Infinity
**说明:**
默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| baselineOffset | number \| string | 设置文本基线的偏移量,默认值0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| letterSpacing | number \| string | 设置文本字符间距。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | 设置文本最小显示字号。
需配合maxFontSize以及maxline或布局大小限制使用,单独设置不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | 设置文本最大显示字号。
需配合minFontSize以及maxline或布局大小限制使用,单独设置不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。
默认值:TextCase.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 组件支持设置文本是否可复制粘贴。
默认值:CopyOptions.None
该接口支持在ArkTS卡片中使用。 | > **说明:** > 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 2acf7d3a89ea1d74e5387040fedb05ddd98fe148..f92eedfb71a4cbc9f502eec478e56a1d1ae80bed 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 @@ -38,6 +38,10 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | 通过正则表达式设置输入过滤器。匹配表达式的输入允许显示,不匹配的输入将被过滤。仅支持单个字符匹配,不支持字符串匹配。
- value:设置正则表达式。
- error:正则匹配失败时,返回被过滤的内容。 | | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。
设置CopyOptions.None时,当前TextArea中的文字无法被复制或剪切,仅支持粘贴。 | +> **说明:** +> +> [通用属性padding](ts-universal-attributes-size.md)的默认值为:
{
 top: 8 vp,
 right: 16 vp,
 bottom: 16 vp,
 left: 8 vp
} + ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index b83500ff338d1136298dc5b085b2dcda8aa391ff..f8398fe4ddf4adb31886db8ecf62998de96f52c7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -43,6 +43,10 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | style9+ | [TextInputStyle](#textinputstyle9枚举说明) | 设置输入框为默认风格或内联输入风格。
默认值:TextInputStyle.Default | | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | 设置输入文本在输入框中的对齐方式。
默认值:TextAlign.Start | +> **说明:** +> +> [通用属性padding](ts-universal-attributes-size.md)的默认值为:
{
 top: 8 vp,
 right: 16 vp,
 bottom: 16 vp,
 left: 8 vp
} + ## EnterKeyType枚举说明 | 名称 | 描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index e82389ae717ae5ca876dd07954276f49af52df95..5151fbeaa14167a3555b60803e823a5fd3f46bd4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -19,6 +19,8 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,26 +30,29 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) ## ToggleType枚举说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | ---------------- | -| Checkbox | 提供单选框样式。
**说明:**
[通用属性padding](ts-universal-attributes-size.md)的默认值为:
{
 top: 14 vp,
 right: 6 vp,
 bottom: 14 vp,
 left: 6 vp
} | +| Checkbox | 提供单选框样式。
**说明:**
[通用属性margin](ts-universal-attributes-size.md)的默认值为:
{
 top: 12 vp,
 right: 12 vp,
 bottom: 12 vp,
 left: 12 vp
} | | Button | 提供状态按钮样式,如果子组件有文本设置,则相应的文本内容会显示在按钮内部。 | -| Switch | 提供开关样式。
**说明:**
[通用属性padding](ts-universal-attributes-size.md)默认值为:
{
 top: 12 vp,
 right: 12 vp,
 bottom: 12 vp,
 left: 12 vp
} | +| Switch | 提供开关样式。
**说明:**
[通用属性margin](ts-universal-attributes-size.md)默认值为:
{
 top: 14 vp,
 right:6 vp,
 bottom: 6 vp,
 left: 14 vp
} | ## 属性 | 名称 | 参数 | 参数描述 | | ---------------- | --------------------------- | ---------------------- | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件打开状态的背景颜色。 | -| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | 设置Switch类型的圆形滑块颜色。
**说明:**
仅对type为ToggleType.Switch生效。 | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件打开状态的背景颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | 设置Switch类型的圆形滑块颜色。
**说明:**
仅对type为ToggleType.Switch生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 事件 | 名称 | 功能描述 | | -------- | -------- | -| onChange(callback: (isOn: boolean) => void) | 开关状态切换时触发该事件。 | +| onChange(callback: (isOn: boolean) => void) | 开关状态切换时触发该事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index dbe81d0fad2e5eb7414e7048e323617297084736..e0541598d1273d8cd0912af47f5c4b93e92eae87 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -1,6 +1,6 @@ # Web -提供具有网页显示能力的Web组件。 +提供具有网页显示能力的Web组件,[@ohos.web.webview](../apis/js-apis-webview.md)提供web控制能力。 > **说明:** > @@ -27,7 +27,7 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------- | ---------------------------------------- | ---- | ------- | -| src | [ResourceStr](ts-types.md) | 是 | 网页资源地址。如果访问本地资源文件,请使用$rawfile或者resource协议。 | +| src | [ResourceStr](ts-types.md) | 是 | 网页资源地址。如果访问本地资源文件,请使用$rawfile或者resource协议。如果加载应用包外沙箱路径的本地资源文件,请使用file://沙箱文件路径。 | | controller | [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller) \| [WebController](#webcontroller) | 是 | 控制器。从API Version 9开始,WebController不在维护,建议使用WebviewController替代。 | **示例:** @@ -84,6 +84,43 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) } ``` + 加载沙箱路径下的本地资源文件 + + 1.通过[globalthis](../../application-models/uiability-data-sync-with-ui.md#uiability和page之间使用globalthis)获取沙箱路径。 + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + let url = 'file://' + globalThis.filesDir + '/xxx.html' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + // 加载沙箱路径文件。 + Web({ src: url, controller: this.controller }) + } + } + } + ``` + + 2.修改MainAbility.ts。 + 以filesDir为例,获取沙箱路径。若想获取其他路径,请参考[应用开发路径](../../application-models/application-context-stage.md#获取应用开发路径)。 + ```ts + // xxx.ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import web_webview from '@ohos.web.webview'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // 通过在globalThis对象上绑定filesDir,可以实现UIAbility组件与UI之间的数据同步。 + globalThis.filesDir = this.context.filesDir + console.log("Sandbox path is " + globalThis.filesDir) + } + } + ``` + ```html @@ -2995,6 +3032,50 @@ onAudioStateChanged(callback: (event: { playing: boolean }) => void) } ``` +### onLoadIntercept10+ + +onLoadIntercept(callback: (event?: { request: WebResourceRequest }) => boolean) + +当Web组件加载url之前触发该回调,用于判断是否阻止此次访问。默认允许加载。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ------- | ---------------------------------------- | --------- | +| request | [Webresourcerequest](#webresourcerequest) | url请求的相关信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------ | +| boolean | 返回true表示阻止此次加载,否则允许此次加载。 | + +**示例:** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onUrlLoadIntercept((event) => { + console.log('url:' + event.request.getRequestUrl()) + console.log('isMainFrame:' + event.request.isMainFrame()) + console.log('isRedirect:' + event.request.isRedirect()) + console.log('isRequestGesture:' + event.request.isRequestGesture()) + return true + }) + } + } + } + ``` + ## ConsoleMessage Web组件获取控制台信息对象。示例代码参考[onConsole事件](#onconsole)。 @@ -3509,6 +3590,8 @@ confirm(priKeyFile : string, certChainFile : string): void confirm(authUri : string): void +**需要权限:** ohos.permission.ACCESS_CERT_MANAGER + 通知Web组件使用指定的凭据(从证书管理模块获得)。 **参数:** @@ -4686,7 +4769,7 @@ setCookie(url: string, value: string): boolean | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | ----- | ------ | ---- | ---- | ----------------- | -| url | string | 是 | - | 要设置的cookie所属的url。 | +| url | string | 是 | - | 要设置的cookie所属的url,建议使用完整的url。 | | value | string | 是 | - | cookie的值。 | **返回值:** 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 1d57e7673a6fc5660667e32b8033429d3ec3df35..06c003747ed24b5b9de3e57391d7905c36642ad8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -683,7 +683,7 @@ fillRect(x: number, y: number, w: number, h: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.fillRect(0,30,100,100) + this.context.fillRect(30,30,100,100) }) } .width('100%') @@ -1922,6 +1922,8 @@ setTransform(transform?: Matrix2D): void 以Matrix2D对象为模板重置现有的变换矩阵并创建新的变换矩阵。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### translate @@ -1977,6 +1979,8 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: 进行图像绘制。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2353,6 +2357,8 @@ toDataURL(type?: string, quality?: number): string 生成一个包含图片展示的URL。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 描述 | 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 03ef8e6c7a980e9383e7ed21cb98ad97832ca51d..c4cf9456bb0f71ec327460373f9481f045acaed8 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 @@ -14,6 +14,8 @@ Canvas(context?: CanvasRenderingContext2D) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -30,7 +32,7 @@ Canvas(context?: CanvasRenderingContext2D) | 名称 | 参数 | 描述 | | ----------------------------- | ---- | -------------------- | -| onReady(event: () => void) | 无 | Canvas组件初始化完成时的事件回调,该事件之后Canvas组件宽高确定且可获取,可使用Canvas相关API进行绘制。 | +| onReady(event: () => void) | 无 | Canvas组件初始化完成时的事件回调,该事件之后Canvas组件宽高确定且可获取,可使用Canvas相关API进行绘制。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **示例:** 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 c6efa1ddbbbc323d26afd22179f0ed1cada1e640..199cbfb2a4223b668b683a448a53f6b648a57564 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 @@ -14,6 +14,8 @@ addColorStop(offset: number, color: string): void 设置渐变断点值,包括偏移和颜色。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** 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 8785206dcef551053042f745837aa8e664757c5d..2890d2890e202d12c13167f04919af42292dbf9a 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 @@ -3,8 +3,20 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 > **说明:** -> -> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 接口 + +ImageBitmap(src: string) + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ------ | -------- | ---- | ------ | ------------------------------------------------------------ | +| src | string | 是 | - | 图片的数据源
**说明:**
- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串 | @@ -12,8 +24,8 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 | 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | ImageBitmap的像素宽度。 | -| height | number | ImageBitmap的像素高度。 | +| width | number | ImageBitmap的像素宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| height | number | ImageBitmap的像素高度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **示例:** @@ -53,4 +65,6 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 close() -释放ImageBitmap对象相关联的所有图形资源。该接口为空接口。 \ No newline at end of file +释放ImageBitmap对象相关联的所有图形资源。该接口为空接口。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 \ No newline at end of file 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 bd1b16a3981851566cb2970203935f439a3c74af..b9a49fb83833aa72194aea7c696ce66c7148ece1 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 @@ -12,9 +12,9 @@ ImageData对象可以存储canvas渲染的像素数据。 | 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | 矩形区域实际像素宽度,单位为px。 | -| height | number | 矩形区域实际像素高度,单位为px。 | -| data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 | +| width | number | 矩形区域实际像素宽度,单位为px。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| height | number | 矩形区域实际像素高度,单位为px。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | > **说明:** > 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 dbad82b43f93702bc3f7f8a00f5572641a2d8833..9d2fd18f2d7b4ab3d72a5acab9d45035211d4ea7 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 @@ -14,6 +14,8 @@ addPath(path: path2D, transform?:Matrix2D): void 将另一个路径添加到当前的路径对象中。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -61,6 +63,8 @@ closePath(): void 将路径的当前点移回到路径的起点,当前点到起点间画一条直线。如果形状已经闭合或只有一个点,则此功能不执行任何操作。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -101,6 +105,8 @@ moveTo(x: number, y: number): void 将路径的当前坐标点移动到目标点,移动过程中不绘制线条。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -148,6 +154,8 @@ lineTo(x: number, y: number): void 从当前点绘制一条直线到目标点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -196,6 +204,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, 创建三次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -245,6 +255,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void 创建二次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -292,6 +304,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, 绘制弧线路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -340,6 +354,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void 依据圆弧经过的点和圆弧半径创建圆弧路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -387,6 +403,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number 在规定的矩形区域绘制一个椭圆。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -437,6 +455,8 @@ rect(x: number, y: number, w: number, h: number): void 创建矩形路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index d26cadcd3f509f6438c97c71d345e5a65413ee64..6161e5389802ff6b94d72cbb3878b00fe16286a7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -18,6 +18,8 @@ 创建数字标记组件。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -31,6 +33,8 @@ 根据字符串创建标记组件。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -41,6 +45,8 @@ ## BadgePosition枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | -------- | -------- | | RightTop | 圆点显示在右上角。 | @@ -49,6 +55,8 @@ ## BadgeStyle对象说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 必填 | 默认值 | 描述 | | ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md index c5fbf12f97fbb91edd0c4fd55fedc189826c1dd9..a3a4e9b6c6dff24a44963b3b481fe9255f01d86c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md @@ -16,6 +16,8 @@ Column(value?: {space?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -28,8 +30,8 @@ Column(value?: {space?: string | number}) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | 设置子组件在水平方向上的对齐格式。
默认值:HorizontalAlign.Center | -| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | 设置子组件在垂直方向上的对齐格式。
默认值:FlexAlign.Start | +| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | 设置子组件在水平方向上的对齐格式。
默认值:HorizontalAlign.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | 设置子组件在垂直方向上的对齐格式。
默认值:FlexAlign.Start
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md index e035856a4c9b0c71dfad2d881c2e8639061841b7..0d20a6caeaf865b9d0b217a1aa418980ff340479 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md @@ -47,6 +47,7 @@ struct ColumnSplitExample { Text('4').width('100%').height(50).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) Text('5').width('100%').height(50).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) } + .borderWidth(1) .resizeable(true) // 可拖动 .width('90%').height('60%') }.width('100%') @@ -54,4 +55,4 @@ struct ColumnSplitExample { } ``` -![zh-cn_image_0000001219982707](figures/zh-cn_image_0000001219982707.gif) +![zh-cn_image_0000001219982708](figures/zh-cn_image_0000001219982708.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md index bd52cece165bb2ab581da8ae3260032baeb48232..ff574a2ceb332fad15eacb6dc2c7aa2f95fbde56 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md @@ -16,6 +16,8 @@ Counter() +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## 事件 @@ -23,8 +25,8 @@ Counter() | 名称 | 功能描述 | | -------- | -------- | -| onInc(event: () => void) | 监听数值增加事件。 | -| onDec(event: () => void) | 监听数值减少事件。 | +| onInc(event: () => void) | 监听数值增加事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onDec(event: () => void) | 监听数值减少事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md index b16e115138d36300c1fddac03c3aa3434a5ce0a0..d018d68f1c8afbfb8720b80deedbac14b3602b3f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md @@ -6,6 +6,7 @@ > > - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > - Flex组件在渲染时存在二次布局过程,因此在对性能有严格要求的场景下建议使用[Column](ts-container-column.md)、[Row](ts-container-row.md)代替。 +> - Flex组件主轴默认不设置时撑满父容器,[Column](ts-container-column.md)、[Row](ts-container-row.md)组件主轴不设置时默认是跟随子节点大小。 ## 子组件 @@ -19,6 +20,8 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle 标准Flex布局容器。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -139,7 +142,7 @@ struct FlexExample2 { } ``` -![zh-cn_image_0000001174264366](figures/zh-cn_image_0000001174264366.PNG) +![zh-cn_image_0000001174264366](figures/zh-cn_image_0000001174264366.png) ```ts // xxx.ets diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md index 2083ff7d49c7296f09a434ac0d805a775f5530d7..c63d3575f0d4b36bbf73ba615bd425d631357237 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md @@ -13,6 +13,8 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColColumnOption, order?: number | GridColColumnOption}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -25,12 +27,14 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| span | number \| GridColColumnOption | 否 | 占用列数。span为0,意味着该元素不参与布局计算,即不会被渲染。
默认值:1。 | -| offset | number \| GridColColumnOption | 否 | 相对于前一个栅格子组件偏移的列数。
默认值:0。 | -| order | number \| GridColColumnOption | 否 | 元素的序号,根据栅格子组件的序号,从小到大对栅格子组件做排序。
默认值:0。 | +| span | number \| GridColColumnOption | 否 | 占用列数。span为0,意味着该元素不参与布局计算,即不会被渲染。
默认值:1。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| offset | number \| GridColColumnOption | 否 | 相对于前一个栅格子组件偏移的列数。
默认值:0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| order | number \| GridColColumnOption | 否 | 元素的序号,根据栅格子组件的序号,从小到大对栅格子组件做排序。
默认值:0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## GridColColumnOption +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数名 | 参数类型 | 必填 | 参数描述 | | ----- | ------ | ---- | ---------------------------------------- | | xs | number | 否 | 最小宽度类型设备。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md index 0e48ee9510e55b54917e45abb27f01dad6bac642..ffa1b45018c52a81e4a2eb1176a85d960babcd1a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md @@ -15,6 +15,8 @@ ## 接口 GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | GutterOption, breakpoints?: BreakPoints, direction?: GridRowDirection}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 |类型|必填|说明| @@ -26,6 +28,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt ## GutterOption +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数名 | 参数类型 | 必填 | 参数描述 | | ----- | ------ | ---- | ---------------------------------------- | | x | Length \| GridRowSizeOption | 否 | 水平gutter option。 | @@ -35,6 +39,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt 栅格在不同宽度设备类型下,栅格列数。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数名 | 参数类型 | 必填 | 参数描述 | | ----- | ------ | ---- | ---------------------------------------- | | xs | number | 否 | 最小宽度类型设备。 | @@ -48,6 +54,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt 栅格在不同宽度设备类型下,gutter的大小。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数名 | 参数类型 | 必填 | 参数描述 | | ----- | ------ | ---- | ---------------------------------------- | | xs | Length | 否 | 最小宽度类型设备。 | @@ -59,6 +67,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt ## BreakPoints +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数名 | 参数类型 | 必填 | 参数描述 | | ----- | ------ | ---- | ---------------------------------------- | | value | Array<string> | 否 | 设置断点位置的单调递增数组。
默认值:["320vp", "600vp", "840vp"] | @@ -73,12 +83,18 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt ``` ## BreakpointsReference枚举类型 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 枚举名 | 描述 | | -------- | -------- | | WindowSize | 以窗口为参照。 | | ComponentSize | 以容器为参照。 | ## GridRowDirection枚举类型 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 枚举名 | 描述 | | -------- | -------- | | Row | 栅格元素按照行方向排列。 | @@ -119,6 +135,8 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt onBreakpointChange(callback: (breakpoints: string) => void) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index a8f0f9b6247b11858d7c291afad7e4a1d7558c4f..0723fe1c2465496f010701f82bd96a44e74bbb21 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -17,6 +17,8 @@ List(value?:{space?: number | string, initialIndex?: number, scroller?: Scroller}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -31,20 +33,22 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。
默认值:Axis.Vertical | -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md),
startMargin?: Length,
endMargin?: Length
} \| null | 设置ListItem分割线样式,默认无分割线。
- strokeWidth: 分割线的线宽。
- color: 分割线的颜色。
- startMargin: 分割线与列表侧边起始端的距离。
- endMargin: 分割线与列表侧边结束端的距离。 | -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off | -| cachedCount | number | 设置列表中ListItem/ListItemGroup的预加载数量,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1 | +| listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。
默认值:Axis.Vertical
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | 设置ListItem分割线样式,默认无分割线。
- strokeWidth: 分割线的线宽。
- color: 分割线的颜色。
- startMargin: 分割线与列表侧边起始端的距离。
- endMargin: 分割线与列表侧边结束端的距离。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| cachedCount | number | 设置列表中ListItem/ListItemGroup的预加载数量,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | editMode(deprecated) | boolean | 声明当前List组件是否处于可编辑模式。
从API version9开始废弃。
默认值:false | -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果。
默认值:EdgeEffect.Spring | -| chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。
默认值:false
- false:不启用链式联动。
- true:启用链式联动。 | -| multiSelectable8+ | boolean | 是否开启鼠标框选。
默认值:false
- false:关闭框选。
- true:开启框选。 | -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | 以列模式为例(listDirection为Axis.Vertical):
lanes用于决定List组件在交叉轴方向按几列布局。
默认值:1
规则如下:
- lanes为指定的数量时,根据指定的数量与List组件的交叉轴宽度来决定每列的宽度;
- lane设置了{minLength,maxLength}时,根据List组件的宽度自适应决定lanes数量(即列数),保证缩放过程中lane的宽度符合{minLength,maxLength}的限制。其中,minLength条件会被优先满足,即优先保证符合ListItem的宽度符合最小宽度限制。例如在列模式下,设置了{minLength: 40vp,maxLength: 60vp},则当List组件宽度为70vp时,ListItem为一列,并且根据alignListItem属性做靠左、居中或者靠右布局;当List组件宽度变化至80vp时,符合两倍的minLength,则ListItem自适应为两列。 | -| alignListItem9+ | ListItemAlign | List交叉轴方向宽度大于ListItem交叉轴宽度 * lanes时,ListItem在List交叉轴方向的布局方式,默认为首部对齐。
默认值:ListItemAlign.Start | -| sticky9+ | StickyStyle | 配合[ListItemGroup](ts-container-listitemgroup.md)组件使用,设置ListItemGroup中header和footer是否要吸顶或吸底。
默认值:StickyStyle.None
**说明:**
sticky属性可以设置为 StickyStyle.Header \| StickyStyle.Footer 以同时支持header吸顶和footer吸底。 | +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果。
默认值:EdgeEffect.Spring
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。
默认值:false
- false:不启用链式联动。
- true:启用链式联动。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| multiSelectable8+ | boolean | 是否开启鼠标框选。
默认值:false
- false:关闭框选。
- true:开启框选。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | 以列模式为例(listDirection为Axis.Vertical):
lanes用于决定List组件在交叉轴方向按几列布局。
默认值:1
规则如下:
- lanes为指定的数量时,根据指定的数量与List组件的交叉轴宽度来决定每列的宽度;
- lane设置了{minLength,maxLength}时,根据List组件的宽度自适应决定lanes数量(即列数),保证缩放过程中lane的宽度符合{minLength,maxLength}的限制。其中,minLength条件会被优先满足,即优先保证符合ListItem的宽度符合最小宽度限制。例如在列模式下,设置了{minLength: 40vp,maxLength: 60vp},则当List组件宽度为70vp时,ListItem为一列,并且根据alignListItem属性做靠左、居中或者靠右布局;当List组件宽度变化至80vp时,符合两倍的minLength,则ListItem自适应为两列。
该接口支持在ArkTS卡片中使用。 | +| alignListItem9+ | ListItemAlign | List交叉轴方向宽度大于ListItem交叉轴宽度 * lanes时,ListItem在List交叉轴方向的布局方式,默认为首部对齐。
默认值:ListItemAlign.Start
该接口支持在ArkTS卡片中使用。 | +| sticky9+ | StickyStyle | 配合[ListItemGroup](ts-container-listitemgroup.md)组件使用,设置ListItemGroup中header和footer是否要吸顶或吸底。
默认值:StickyStyle.None
该接口支持在ArkTS卡片中使用。
**说明:**
sticky属性可以设置为 StickyStyle.Header \| StickyStyle.Footer 以同时支持header吸顶和footer吸底。 | ## ListItemAlign9+枚举说明 +该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | -------------------------------------- | | Start | ListItem在List中,交叉轴方向首部对齐。 | @@ -53,6 +57,8 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? ## StickyStyle9+枚举说明 +该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | -------------------------------------- | | None | ListItemGroup的header不吸顶,footer不吸底。 | @@ -66,13 +72,13 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | 名称 | 功能描述 | | -------- | -------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | 当List组件在编辑模式时,点击ListItem右边出现的删除按钮时触发。
从API version9开始废弃。
- index: 被删除的列表项的索引值。 | -| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | 列表滑动时触发。
- scrollOffset: 滑动偏移量。
- [scrollState](#scrollstate枚举说明): 当前滑动状态。 | -| onScrollIndex(event: (start: number, end: number) => void) | 列表滑动时触发。
计算索引值时,ListItemGroup作为一个整体占一个索引值,不计算ListItemGroup内部ListItem的索引值。
- start: 滑动起始位置索引值。
- end: 滑动结束位置索引值。 | -| onReachStart(event: () => void) | 列表到达起始位置时触发。 | -| onReachEnd(event: () => void) | 列表到底末尾位置时触发。 | -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | 列表开始滑动时触发,事件参数传入即将发生的滑动量,事件处理函数中可根据应用场景计算实际需要的滑动量并作为事件处理函数的返回值返回,列表将按照返回值的实际滑动量进行滑动。
\- offset:即将发生的滑动量。
\- state:当前滑动状态。
- offsetRemain:水平方向实际滑动量。 | -| onScrollStart9+(event: () => void) | 列表滑动开始时触发。手指拖动列表或列表的滚动条触发的滑动开始时,会触发该事件。使用[Scroller](ts-container-scroll.md#scroller)滑动控制器触发的滑动,不会触发该事件。 | -| onScrollStop(event: () => void) | 列表滑动停止时触发。手拖动列表或列表的滚动条触发的滑动,手离开屏幕并且滑动停止时会触发该事件;使用[Scroller](ts-container-scroll.md#scroller)滑动控制器触发的滑动,不会触发该事件。 | +| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | 列表滑动时触发。
- scrollOffset: 滑动偏移量。
- [scrollState](#scrollstate枚举说明): 当前滑动状态。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onScrollIndex(event: (start: number, end: number) => void) | 列表滑动时触发。
计算索引值时,ListItemGroup作为一个整体占一个索引值,不计算ListItemGroup内部ListItem的索引值。
- start: 滑动起始位置索引值。
- end: 滑动结束位置索引值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onReachStart(event: () => void) | 列表到达起始位置时触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onReachEnd(event: () => void) | 列表到底末尾位置时触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | 列表开始滑动时触发,事件参数传入即将发生的滑动量,事件处理函数中可根据应用场景计算实际需要的滑动量并作为事件处理函数的返回值返回,列表将按照返回值的实际滑动量进行滑动。
\- offset:即将发生的滑动量。
\- state:当前滑动状态。
- offsetRemain:实际滑动量。
该接口支持在ArkTS卡片中使用。
**说明:**
当listDirection的值为Axis.Vertical时,返回垂直方向滑动量,当listDirection的值为Axis.Horizontal时,返回水平方向滑动量。 | +| onScrollStart9+(event: () => void) | 列表滑动开始时触发。手指拖动列表或列表的滚动条触发的滑动开始时,会触发该事件。使用[Scroller](ts-container-scroll.md#scroller)滑动控制器触发的带动画的滑动,动画开始时会触发该事件。
该接口支持在ArkTS卡片中使用。 | +| onScrollStop(event: () => void) | 列表滑动停止时触发。手拖动列表或列表的滚动条触发的滑动,手离开屏幕并且滑动停止时会触发该事件;使用[Scroller](ts-container-scroll.md#scroller)滑动控制器触发的带动画的滑动,动画停止会触发该事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | onItemMove(event: (from: number, to: number) => boolean) | 列表元素发生移动时触发。
- from: 移动前索引值。
- to: 移动后索引值。 | | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | 开始拖拽列表元素时触发。
- event: 见[ItemDragInfo对象说明](ts-container-grid.md#itemdraginfo对象说明)。
- itemIndex: 被拖拽列表元素索引值。 | | onItemDragEnter(event: (event: ItemDragInfo) => void) | 拖拽进入列表元素范围内时触发。
- event: 见[ItemDragInfo对象说明](ts-container-grid.md#itemdraginfo对象说明)。 | @@ -82,6 +88,8 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? ## ScrollState枚举说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------ | ------------------------- | | Idle | 未滑动状态。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md index 67ea6de032704abd2d314b8b8a9a040572f39748..22799b3ac2607dc2e0817862f33fafcd077cd1df 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -16,6 +16,8 @@ ListItem(value?: string) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: @@ -24,7 +26,7 @@ ListItem(value?: string) | -------- | -------- | -------- | | sticky(deprecated) | [Sticky](#stickydeprecated枚举说明) | 设置ListItem吸顶效果。
默认值:Sticky.None
从API version9开始废弃,推荐使用[List组件sticky属性](ts-container-list.md#属性)。 | | editable(deprecated) | boolean \| [EditMode](#editmodedeprecated枚举说明) | 当前ListItem元素是否可编辑,进入编辑模式后可删除或移动列表项。
从API version9开始废弃。
默认值:false | -| selectable8+ | boolean | 当前ListItem元素是否可以被鼠标框选。
**说明:**
外层List容器的鼠标框选开启时,ListItem的框选才生效。
默认值:true | +| selectable8+ | boolean | 当前ListItem元素是否可以被鼠标框选。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
外层List容器的鼠标框选开启时,ListItem的框选才生效。
默认值:true | | swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9枚举说明),
} | 用于设置ListItem的划出组件。
- start: ListItem向右划动时item左边的组件(List垂直布局时)或ListItem向下划动时item上方的组件(List水平布局时)。
- end: ListItem向左划动时item右边的组件(List垂直布局时)或ListItem向上划动时item下方的组件(List水平布局时)。
- edgeEffect: 滑动效果。
| ## Sticky(deprecated)枚举说明 @@ -53,7 +55,7 @@ ListItem(value?: string) | 名称 | 功能描述 | | -------- | -------- | -| onSelect(event: (isSelected: boolean) => void)8+ | ListItem元素被鼠标框选的状态改变时触发回调。
isSelected:进入鼠标框选范围即被选中返回true, 移出鼠标框选范围即未被选中返回false。 | +| onSelect(event: (isSelected: boolean) => void)8+ | ListItem元素被鼠标框选的状态改变时触发回调。
isSelected:进入鼠标框选范围即被选中返回true, 移出鼠标框选范围即未被选中返回false。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-relativecontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-relativecontainer.md index 4eb27d9e09e72015a1e7c0c10b6ecbf8d38ec155..6390be6bf5545188807777190731bc67143aab6b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-relativecontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-relativecontainer.md @@ -31,6 +31,8 @@ RelativeContainer() +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## 示例 ```ts diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md index 4942b0cc3ee6ee779530dac83059bb585e9616a8..69d6b435712382434f64b8c042755fd654dd2dc8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md @@ -16,6 +16,8 @@ Row(value?:{space?: number | string }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -27,8 +29,8 @@ Row(value?:{space?: number | string }) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | 设置子组件在垂直方向上的对齐格式。
默认值:VerticalAlign.Center | -| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | 设置子组件在水平方向上的对齐格式。
FlexAlign.Start | +| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | 设置子组件在垂直方向上的对齐格式。
默认值:VerticalAlign.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | 设置子组件在水平方向上的对齐格式。
FlexAlign.Start
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index 9996564d394d9c646f255a0d132d8c601638c3e3..477df9e35027daa97db37db06e3176f12c112b55 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -18,6 +18,12 @@ Scroll(scroller?: Scroller) +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| scroller | [Scroller](#scroller) | 否 | 可滚动组件的控制器。用于与可滚动组件进行绑定。 | + ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: @@ -42,12 +48,12 @@ Scroll(scroller?: Scroller) | 名称 | 功能描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | 每帧开始滚动时触发,事件参数传入即将发生的滚动量,事件处理函数中可根据应用场景计算实际需要的滚动量并作为事件处理函数的返回值返回,Scroll将按照返回值的实际滚动量进行滚动。
\- offset:即将发生的滚动量。
\- state:当前滚动状态。
- offsetRemain:水平方向实际滚动量。 | +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | 每帧开始滚动时触发,事件参数传入即将发生的滚动量,事件处理函数中可根据应用场景计算实际需要的滚动量并作为事件处理函数的返回值返回,Scroll将按照返回值的实际滚动量进行滚动。
\- offset:即将发生的滚动量。
\- state:当前滚动状态。
- offsetRemain:实际滚动量。 | | onScroll(event: (xOffset: number, yOffset: number) => void) | 滚动事件回调, 返回滚动时水平、竖直方向偏移量。 | | onScrollEdge(event: (side: Edge) => void) | 滚动到边缘事件回调。 | -| onScrollEnd(event: () => void) | 滚动停止事件回调。
该事件从API9开始废弃,使用onScrollStop事件替代。 | -| onScrollStart9+(event: () => void) | 滚动开始时触发。手指拖动Scroll或拖动Scroll的滚动条触发的滚动开始时,会触发该事件。使用[Scroller](#scroller)滚动控制器触发的滚动,不会触发该事件。 | -| onScrollStop9+(event: () => void) | 滚动停止时触发。手拖动Scroll或拖动Scroll的滚动条触发的滚动,手离开屏幕并且滚动停止时会触发该事件;使用[Scroller](#scroller)滚动控制器触发的滚动,不会触发该事件。 | +| onScrollEnd(deprecated) (event: () => void) | 滚动停止事件回调。
该事件从API9开始废弃,使用onScrollStop事件替代。 | +| onScrollStart9+(event: () => void) | 滚动开始时触发。手指拖动Scroll或拖动Scroll的滚动条触发的滚动开始时,会触发该事件。使用[Scroller](#scroller)滚动控制器触发的带动画的滚动,动画开始时会触发该事件。 | +| onScrollStop9+(event: () => void) | 滚动停止时触发。手拖动Scroll或拖动Scroll的滚动条触发的滚动,手离开屏幕并且滚动停止时会触发该事件。使用[Scroller](#scroller)滚动控制器触发的带动画的滚动,动画停止时会触发该事件。 | > **说明:** > @@ -55,7 +61,7 @@ Scroll(scroller?: Scroller) ## Scroller -可滚动容器组件的控制器,可以将此组件绑定至容器组件,然后通过它控制容器组件的滚动,同一个控制器不可以控制多个容器组件,目前支持绑定到List、Scroll、ScrollBar上。 +可滚动容器组件的控制器,可以将此组件绑定至容器组件,然后通过它控制容器组件的滚动,同一个控制器不可以控制多个容器组件,目前支持绑定到List、Scroll、ScrollBar、Grid、WaterFlow上。 ### 导入对象 @@ -76,8 +82,8 @@ scrollTo(value: { xOffset: number | string, yOffset: number | string, animation? | 参数名 | 参数类型 | 必填 | 参数描述 | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| xOffset | Length | 是 | 水平滑动偏移。 | -| yOffset | Length | 是 | 竖直滑动偏移。 | +| xOffset | number | string | 是 | 水平滑动偏移。 | +| yOffset | number | string | 是 | 竖直滑动偏移。 | | animation | {
duration: number,
curve: [Curve](ts-appendix-enums.md#curve)
} | 否 | 动画配置:
- duration: 滚动时长设置。
- curve: 滚动曲线设置。 | @@ -86,7 +92,7 @@ scrollTo(value: { xOffset: number | string, yOffset: number | string, animation? scrollEdge(value: Edge): void -滚动到容器边缘。 +滚动到容器边缘,不区分滚动轴方向,Edge.Top和Edge.Start表现相同,Edge.Bottom和Edge.End表现相同。 **参数:** @@ -111,7 +117,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void ### currentOffset -currentOffset() +currentOffset(): { xOffset: number, yOffset: number } 返回当前的滚动偏移量。 @@ -133,7 +139,7 @@ scrollToIndex(value: number): void > **说明:** > -> 仅支持Grid、list组件。 +> 仅支持Grid、List组件。 **参数:** @@ -152,7 +158,7 @@ scrollBy(dx: Length, dy: Length): void > **说明:** > -> 仅支持Scroll组件。 +> 仅支持Scroll、ScrollBar、Grid、List组件。 **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md index 9b329c79b9806056213a6d191fbfd6d7b2d2486c..385f3fa1b2104c4eea94ca61a055ae4115fe45cf 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md @@ -16,11 +16,21 @@ Stack(value?: { alignContent?: Alignment }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -| alignContent | [Alignment](ts-appendix-enums.md#alignment) | 否 | 设置子组件在容器内的对齐方式。
默认值:Alignment.Center | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ------------ | ------------------------------------------- | ---- | ----------------------------------------------------------- | +| alignContent | [Alignment](ts-appendix-enums.md#alignment) | 否 | 设置子组件在容器内的对齐方式。
默认值:Alignment.Center | + +## 属性 + +除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: + +| 名称 | 参数类型 | 描述 | +| ------------ | ------------------------------------------- | ------------------------------ | +| alignContent | [Alignment](ts-appendix-enums.md#alignment) | 设置子组件在容器内的对齐方式。
默认值:Alignment.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index e9b00bc26c5a7632c0ad12531130154b0cbdde77..66cdc22b56b222119f87550419fbdb4a923b7178 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -30,7 +30,7 @@ Swiper(controller?: SwiperController) | 名称 | 参数类型 | 描述 | | --------------------------- | ---------------------------------------- | ---------------------------------------- | | index | number | 设置当前在容器中显示的子组件的索引值。
默认值:0 | -| autoPlay | boolean | 子组件是否自动播放,自动播放状态下,导航点不可操作。
默认值:false | +| autoPlay | boolean | 子组件是否自动播放。
默认值:false | | interval | number | 使用自动播放时播放的时间间隔,单位为毫秒。
默认值:3000 | | indicator | boolean | 是否启用导航点指示器。
默认值:true | | loop | boolean | 是否开启循环。
设置为true时表示开启循环,在LazyForEach懒循环加载模式下,加载的组件数量建议大于5个。
默认值:true | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md index dcd23fcc36c703fc73f6615056b47e9a766fc3eb..a9082e59775478927413364a1f807c83ff9a2ced 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -29,6 +29,7 @@ TabContent() > **说明:** > - TabContent组件不支持设置通用宽度属性,其宽度默认撑满Tabs父组件。 > - TabContent组件不支持设置通用高度属性,其高度由Tabs父组件高度与TabBar组件高度决定。 +> - TabContent组件不支持内容过长时页面的滑动,如需页面滑动,可嵌套List使用。 ## SubTabBarStyle9+ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md index db6b7734889a55af7884e2be2de46c619861dbc3..63ede8489f4221fdbd710f1b7851f6b808aaf46e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md @@ -16,6 +16,8 @@ Circle(options?: {width?: string | number, height?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -29,17 +31,17 @@ Circle(options?: {width?: string | number, height?: string | number}) | 名称 | 类型 | 描述 | | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | 设置填充区域颜色。
默认值:Color.Black | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置填充区域透明度。
默认值:1 | -| stroke | [ResourceColor](ts-types.md) | 设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | 设置边框间隙。
默认值:[] | -| strokeDashOffset | number \| string | 边框绘制起点的偏移量。
默认值:0 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 设置边框端点绘制样式。
默认值:LineCapStyle.Butt | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | 设置边框拐角绘制样式。
默认值:LineJoinStyle.Miter | -| strokeMiterLimit | number \| string | 设置斜接长度与边框宽度比值的极限值。
默认值:4
**说明:**
Circle组件无法设置尖角图形,该属性设置无效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置边框透明度。
默认值:1
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 设置边框宽度。
默认值:1 | -| antiAlias | boolean | 是否开启抗锯齿效果。
默认值:true | +| fill | [ResourceColor](ts-types.md) | 设置填充区域颜色。
默认值:Color.Black
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置填充区域透明度。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| stroke | [ResourceColor](ts-types.md) | 设置边框颜色,不设置时,默认没有边框。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashArray | Array<Length> | 设置边框间隙。
默认值:[]
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashOffset | number \| string | 边框绘制起点的偏移量。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 设置边框端点绘制样式。
默认值:LineCapStyle.Butt
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | 设置边框拐角绘制样式。
默认值:LineJoinStyle.Miter
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 设置斜接长度与边框宽度比值的极限值。
默认值:4
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Circle组件无法设置尖角图形,该属性设置无效。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置边框透明度。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | +| strokeWidth | Length | 设置边框宽度。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| antiAlias | boolean | 是否开启抗锯齿效果。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md index 559a8791ece5b03ef04af063717555a58427429f..bb7cd917cad709a29d4fdebea42497df76e5f1e0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md @@ -16,6 +16,8 @@ Ellipse(options?: {width?: string | number, height?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -29,17 +31,17 @@ Ellipse(options?: {width?: string | number, height?: string | number}) | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - |设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。
**说明:**
Ellipse组件无法设置尖角图形,该属性设置无效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置边框宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| stroke | [ResourceColor](ts-types.md) | - |设置边框颜色,不设置时,默认没有边框。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Ellipse组件无法设置尖角图形,该属性设置无效。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | +| strokeWidth | Length | 1 | 设置边框宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md index 8cbe017c22667593ddd27d1063489efd3bfcc44f..85f6d1289ce2b38e447f146ce547e094e9e1d9ee 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md @@ -15,6 +15,8 @@ Line(value?: {width?: string | number, height?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -29,19 +31,19 @@ Line(value?: {width?: string | number, height?: string | number}) | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| startPoint | Array<Length> | [0, 0] | 直线起点坐标点(相对坐标),单位vp。 | -| endPoint | Array<Length> | [0, 0] | 直线终点坐标点(相对坐标),单位vp。 | -| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 设置填充区域颜色。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | -| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。
**说明:**
Line组件无法设置锐角图形,该属性设置无效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置线条宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| startPoint | Array<Length> | [0, 0] | 直线起点坐标点(相对坐标),单位vp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| endPoint | Array<Length> | [0, 0] | 直线终点坐标点(相对坐标),单位vp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashArray | Array<Length> | [] | 设置线条间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Line组件无法设置锐角图形,该属性设置无效。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | +| strokeWidth | Length | 1 | 设置线条宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 02ccd3b9aaf627be618132b2c023a634fdd004e6..2aeb1cf919c9cd67e3ade9f106b390240b8edc08 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -15,6 +15,8 @@ Path(value?: { width?: number | string; height?: number | string; commands?: string }) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -29,18 +31,18 @@ Path(value?: { width?: number | string; height?: number | string; commands?: str | 名称 | 类型 | 默认值 | 描述 | | -------- | ----------------------------------- | ---- | ---------------------------------------- | -| commands | string | '' | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](ts-pixel-units.md)。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - |设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置线条宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| commands | string | '' | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](ts-pixel-units.md)。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| stroke | [ResourceColor](ts-types.md) | - |设置边框颜色,不设置时,默认没有边框。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashArray | Array<Length> | [] | 设置线条间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeWidth | Length | 1 | 设置线条宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。| commands支持的绘制命令如下: diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md index 5ec83e3c362a6b4b9038e353633f9018c256af46..1e63df5002792b90232dd73cec7b10643a90ab39 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md @@ -16,6 +16,8 @@ Polygon(value?: {width?: string | number, height?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -30,23 +32,25 @@ Polygon(value?: {width?: string | number, height?: string | number}) | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | 多边形的顶点坐标列表。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置边框宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| points | Array<Point> | [] | 多边形的顶点坐标列表。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeWidth | Length | 1 | 设置边框宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## Point 点坐标类型。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型定义 | 描述 | | --------- | -------------------- | ------------------------------------------------------------ | | Point | [number, number] | 第一个参数为x轴坐标,第二个参数为y轴坐标(相对坐标)。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md index afa18e7f7af8cf3abb85c65b5fba727e7b40e42d..4cb64ed2723d69c7139e087bcc93e89f20bfe3a1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md @@ -16,6 +16,8 @@ Polyline(value?: {width?: string | number, height?: string | number}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -30,23 +32,25 @@ Polyline(value?: {width?: string | number, height?: string | number}) | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | 折线经过坐标点列表。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置线条宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| points | Array<Point> | [] | 折线经过坐标点列表。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashArray | Array<Length> | [] | 设置线条间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeWidth | Length | 1 | 设置线条宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## Point 点坐标类型。 +
从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型定义 | 描述 | | --------- | -------------------- | ------------------------------------------------------------ | | Point | [number, number] | 第一个参数为x轴坐标,第二个参数为y轴坐标(相对坐标)。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index fb41d1b6a89b4814bd7a222ed2462b55101b2882..889b9f2f0d91311d2ec934cc8e46f6f4a67dc61b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -17,6 +17,8 @@ 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}) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -34,20 +36,20 @@ Rect(value?: {width?: string | number,height?: string | number,radius?: string | | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| radiusWidth | string \| number | 0 | 圆角的宽度,仅设置宽时宽高一致。 | -| radiusHeight | string \| number | 0 | 圆角的高度,仅设置高时宽高一致。 | -| radius | string \| number \| Array<string \| number> | 0 | 圆角半径大小。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | Length | 1 | 设置边框宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| radiusWidth | string \| number | 0 | 圆角的宽度,仅设置宽时宽高一致。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| radiusHeight | string \| number | 0 | 圆角的高度,仅设置高时宽高一致。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| radius | string \| number \| Array<string \| number> | 0 | 圆角半径大小。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashArray | Array<Length> | [] | 设置边框间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeWidth | Length | 1 | 设置边框宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 示例 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 22231ba443c6382fb645d04b9833424324be8e55..7586e24fe930715e2b7f3b6cf6d12dce50043dca 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,6 +21,8 @@ Shape(value?: PixelMap) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -34,19 +36,19 @@ Shape(value?: PixelMap) | 名称 | 类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | 形状的视口。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。 | -| strokeWidth | number \| string | 1 | 设置边框宽度。 | -| antiAlias | boolean | true | 是否开启抗锯齿效果。 | -| mesh8+ | Array<number>,number,number | [],0,0 | 设置mesh效果。第一个参数为长度(column + 1)* (row + 1)* 2的数组,它记录了扭曲后的位图各个顶点位置,第二个参数为mesh矩阵列数column,第三个参数为mesh矩阵行数row。 | +| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | 形状的视口。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashArray | Array<Length> | [] | 设置边框间隙。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeMiterLimit | number \| string | 4 | 设置斜接长度与边框宽度比值的极限值。斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。
**说明:**
该属性取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。
**说明:**
该属性的取值范围是[0.0, 1.0],若给定值小于0.0,则取值为0.0;若给定值大于1.0,则取值为1.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| strokeWidth | number \| string | 1 | 设置边框宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| antiAlias | boolean | true | 是否开启抗锯齿效果。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| mesh8+ | Array<number>,number,number | [],0,0 | 设置mesh效果。第一个参数为长度(column + 1)* (row + 1)* 2的数组,它记录了扭曲后的位图各个顶点位置,第二个参数为mesh矩阵列数column,第三个参数为mesh矩阵行数row。
从API version 9开始,该接口支持在ArkTS卡片中使用。| ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md index e6511abfc7f4e969909655b05594e93df9764542..ca5bc50d38e9bf0b2d2d230c3cff6256239df3be 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -6,9 +6,10 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - animateTo(value: AnimateParam, event: () => void): void +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数 | 类型 | 是否必填 | 描述 | | ---------------- | ------------ | -------------------- | -------------------- | | value | [AnimateParam](#animateparam对象说明) | 是 | 设置动画效果相关参数。 | @@ -18,13 +19,13 @@ animateTo(value: AnimateParam, event: () => void): void | 名称 | 类型 | 描述 | | -------- | -------- | -------- | -| duration | number | 动画持续时间,单位为毫秒。
默认值:1000 | +| duration | number | 动画持续时间,单位为毫秒。
默认值:1000
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
- 在ArkTS卡片上最大动画持续时间为1000毫秒,若超出则固定为1000毫秒。 | | tempo | number | 动画的播放速度,值越大动画播放越快,值越小播放越慢,为0时无动画效果。
默认值:1.0 | -| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | 动画曲线。
默认值:Curve.Linear | +| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | 动画曲线。
默认值:Curve.Linear
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | delay | number | 单位为ms(毫秒),默认不延时播放。
默认值:0 | | iterations | number | 默认播放一次,设置为-1时表示无限次播放。
默认值:1 | -| playMode | [PlayMode](ts-appendix-enums.md#playmode) | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal | -| onFinish | () => void | 动效播放完成回调。 | +| playMode | [PlayMode](ts-appendix-enums.md#playmode) | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onFinish | () => void | 动效播放完成回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 @@ -41,7 +42,7 @@ struct AnimateToExample { build() { Column() { - Button('change width and height') + Button('change size') .width(this.widthSize) .height(this.heightSize) .margin(30) @@ -56,8 +57,8 @@ struct AnimateToExample { console.info('play end') } }, () => { - this.widthSize = 100 - this.heightSize = 50 + this.widthSize = 150 + this.heightSize = 60 }) } else { animateTo({}, () => { @@ -76,7 +77,7 @@ struct AnimateToExample { curve: Curve.Friction, delay: 500, iterations: -1, // 设置-1表示动画无限循环 - playMode: PlayMode.AlternateReverse, + playMode: PlayMode.Alternate, onFinish: () => { console.info('play end') } @@ -89,10 +90,4 @@ struct AnimateToExample { } ``` -示意图: - -![animation](figures/animation.PNG) - -点击第一个按钮播放改变按钮大小的动画,点击第二个按钮播放按钮顺时针旋转90度的动画。 - -![animation1](figures/animation1.PNG) \ No newline at end of file +![animation1](figures/animation1.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md b/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md index ba54d01040d4c372cbcab714cd3b7c7e2f8b38f3..60a2352f3cab73db8afd799b52cc2ebce74186c9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -118,9 +118,9 @@ requestFullscreen(value: boolean) **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| ----- | ------- | ---- | --------------------- | -| value | boolean | 是 | 是否全屏播放。
默认值:false | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ------ | -------- | ---- | -------------------------------------------------- | +| value | boolean | 是 | 是否全屏(填充满应用窗口)播放。
默认值:false | ### exitFullscreen @@ -173,7 +173,7 @@ struct VideoCreateComponent { previewUri: this.previewUri, currentProgressRate: this.curRate, controller: this.controller - }).width(800).height(600) + }).width('100%').height(600) .autoPlay(this.isAutoPlay) .controls(this.showControls) .onStart(() => { @@ -186,7 +186,7 @@ struct VideoCreateComponent { console.info('onFinish') }) .onError(() => { - console.info('onFinish') + console.info('onError') }) .onPrepared((e) => { console.info('onPrepared is ' + e.duration) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 604ebcbaa2793c48bf670705786324483fe094f8..2455f37d8358291ee204ed57fff3b1fce99e8911 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -11,7 +11,7 @@ ## 接口 -CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam}) +CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam, showInSubWindow?: boolean}) **参数:** @@ -26,8 +26,9 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | customStyle | boolean | 否 | 弹窗容器样式是否自定义。
默认值:false,弹窗容器的宽度根据栅格系统自适应,不跟随子节点;高度自适应子节点,最大为窗口高度的90%;圆角为24vp。 | | gridCount8+ | number | 否 | 弹窗宽度占[栅格宽度](../../ui/ui-ts-layout-grid-container-new.md)的个数。
默认值为4,异常值按默认值处理,最大栅格数为系统最大栅格数。 | | maskColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 否 | 自定义蒙层颜色。
默认值: 0x33000000 | -| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗弹出的动画效果相关参数。 | +| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗弹出的动画效果相关参数。
注意:当iterations为奇数,playMode设置为Reverse,动画结束时,弹窗不显示。 | | closeAniamtion10+| [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗关闭的动画效果相关参数。 | +| showInSubWindow10+| boolean | 否 | 是否在子窗口显示弹窗。
默认值:false,在子窗口不显示弹窗。
**说明**:showInSubWindow为true的弹窗无法触发显示另一个showInSubWindow为true的弹窗。 | ## CustomDialogController diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md index adb197b0bff707b0f237933e1b48e21689e1154a..5218253c46b068d548aac0ffd9fb70a6198962e1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md @@ -25,7 +25,7 @@ struct MotionPathExample { build() { Column() { - Button('click me') + Button('click me').margin(50) // 执行动画:从起点移动到(300,200),再到(300,500),再到终点 .motionPath({ path: 'Mstart.x start.y L300 200 L300 500 Lend.x end.y', from: 0.0, to: 1.0, rotatable: true }) .onClick(() => { 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 0473859c7008b47b62f869694e13f2be2e545056..0bb0e484f4c8bb852f381ff6b5d9c5ea73aeb12f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -727,7 +727,7 @@ fillRect(x: number, y: number, w: number, h: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillRect(0,30,100,100) + this.offContext.fillRect(30,30,100,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2411,6 +2411,8 @@ toDataURL(type?: string, quality?: number): string 生成一个包含图片展示的URL。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md index 654b88ab931a8adbfd3f66d67f09ab33e145e817..d2de0f74094efb91025691580bef33c1e9e954b8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -15,14 +15,14 @@ 提供其他单位与px单位互相转换的方法。 -| 接口 | 描述 | -| ---------------------------------------- | ---------------------- | -| vp2px(value : number) : number | 将vp单位的数值转换为以px为单位的数值。 | -| px2vp(value : number) : number | 将px单位的数值转换为以vp为单位的数值。 | -| fp2px(value : number) : number | 将fp单位的数值转换为以px为单位的数值。 | -| px2fp(value : number) : number | 将px单位的数值转换为以fp为单位的数值。 | -| lpx2px(value : number) : number | 将lpx单位的数值转换为以px为单位的数值。 | -| px2lpx(value : number) : number | 将px单位的数值转换为以lpx为单位的数值。 | +| 接口 | 描述 | +| --------------------------------------------------- | ------------------------------------------------------------ | +| vp2px(value : number) : number | 将vp单位的数值转换为以px为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| px2vp(value : number) : number | 将px单位的数值转换为以vp为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fp2px(value : number) : number | 将fp单位的数值转换为以px为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| px2fp(value : number) : number | 将px单位的数值转换为以fp为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| lpx2px(value : number) : number | 将lpx单位的数值转换为以px为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| px2lpx(value : number) : number | 将px单位的数值转换为以lpx为单位的数值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index 1726ad14146e9f2c4aeb6919e3e031aa661fdfec..d3ce69c6dae140a33f2a6f68ebf0757a9c9fc09c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。 | -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。
repeat:设置背景图片的重复样式,默认不重复。 | -| backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | 设置背景图像的高度和宽度。当输入为{width: Length, height: Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。
默认值:ImageSize.Auto | -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置,即相对于组件左上角的坐标。
默认值:
{
x: 0,
y: 0
}
x和y值设置百分比时,偏移量是相对组件自身宽高计算的。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。
repeat:设置背景图片的重复样式,默认不重复。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | 设置背景图像的高度和宽度。当输入为{width: Length, height: Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。
默认值:ImageSize.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置,即相对于组件左上角的坐标。
默认值:
{
x: 0,
y: 0
}
x和y值设置百分比时,偏移量是相对组件自身宽高计算的。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md index cb368b39322eff4969717eafe7fd80cb7b1af116..50b1bc3a158306be1a402a59589116586986d95e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md @@ -10,17 +10,16 @@ ## 属性 -| 名称 | 参数类型 | 描述 | +| 名称 | 参数 | 描述 | | -------------------- | ----------------------- | ------------------------ | -| backgroundBlurStyle | [BlurStyle](#blurstyle) | 为当前组件提供一种在背景和内容之间的模糊能力,入参为模糊材质。| +| backgroundBlurStyle | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),
options10+?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10对象说明) | 为当前组件提供一种在背景和内容之间的模糊能力。
value: 背景模糊样式。模糊样式中封装了模糊半径、蒙版颜色、蒙版透明度、饱和度四个参数。
options: 可选参数,背景模糊选项。
该接口支持在ArkTS卡片中使用。 | + +## BackgroundBlurStyleOptions10+对象说明 -## BlurStyle - - | 名称 | 描述 | - | ------- | ---------- | - | Thin | 轻薄材质。 | - | Regular | 普通厚度材质。 | - | Thick | 厚材质。 | +| 名称 | 参数类型 | 必填 | 描述 | +| ----------- | ------| ------ | ------ | +| colorMode10+ | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | 否 | 背景模糊效果使用的深浅色模式。
默认值:ThemeColorMode.System | +| adaptiveColor10+ | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | 否 | 背景模糊效果使用的取色模式。
默认值:AdaptiveColor.Default | ## 示例 @@ -28,16 +27,16 @@ // xxx.ets @Entry @Component -struct Index { +struct BackgroundBlurStyleDemo { build() { Column() { Row() { Text("Thin Material") } - .width(350) - .height(300) - .backgroundBlurStyle(BlurStyle.Thin) - .position({ x: "15%", y: "30%" }) + .width('50%') + .height('50%') + .backgroundBlurStyle(BlurStyle.Thin, { colorMode: ThemeColorMode.Light, adaptiveColor: AdaptiveColor.Default }) + .position({ x: '15%', y: '30%' }) } .height('100%') .width('100%') @@ -46,4 +45,4 @@ struct Index { } } ``` -![zh-cn_image_background_blur_style](figures/zh-cn_image_background_blur_style.png) \ No newline at end of file +![zh-cn_image_background_blur_style](figures/zh-cn_image_background_blur_style.png) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index b41a408db85dccf042901b5dedcee65367dc18cd..2ade5dcdb6bc59452b253df6a4c73cacd7baae72 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -10,10 +10,12 @@ | 名称 | 参数类型 | 描述 | | ---------- | ---------------------------------------- | --------------------------------------- | -| borderImage | [BorderImageOption](#borderimageoption对象说明) | 图片边框或者渐变色边框设置接口。 | +| borderImage | [BorderImageOption](#borderimageoption对象说明) | 图片边框或者渐变色边框设置接口。
该接口支持在ArkTS卡片中使用。 | ## BorderImageOption对象说明 +该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 描述 | | ---------- | ---------------------------------------- | --------------------------------------- | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。
**说明:** 边框图源仅适用于容器组件,如Row、Column、Flex,在非容器组件上使用会失效。 | @@ -23,9 +25,10 @@ | repeat | [RepeatMode](#repeatmode枚举说明) | 设置边框图片的重复方式。
默认值:RepeatMode.Stretch | | fill | boolean | 设置边框图片中心填充。
默认值:false | - ## RepeatMode枚举说明 +该接口支持在ArkTS卡片中使用。 + | 名称 | 描述 | | ------- | ----------------------------------- | | Repeat | 被切割图片重复铺平在图片边框上,超出的部分会被剪裁。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md index 58a64f62891cce602d65efe18cd04ee46c92abb5..e52c019db54f0f0b6bc7c45e1de40bd46aaabb4f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md @@ -13,11 +13,11 @@ | 名称 | 参数类型 | 描述 | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| border | {
width?: [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+,
color?:  [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+,
radius?:  [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+,
style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+
} | 统一边框样式设置接口。
- width:设置边框宽度。
- color:设置边框颜色。
- radius:设置边框圆角半径。
- style:设置边框样式。 | -| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+ | 设置元素的边框样式。
默认值:BorderStyle.Solid | -| borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+ | 设置元素的边框宽度,不支持百分比。 | -| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+ | 设置元素的边框颜色。
默认值:Color.Black | -| borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+ | 设置元素的边框圆角半径,不支持百分比。 | +| border | {
width?: [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+,
color?:  [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+,
radius?:  [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+,
style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+
} | 统一边框样式设置接口。
- width:设置边框宽度。
- color:设置边框颜色。
- radius:设置边框圆角半径。
- style:设置边框样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+ | 设置元素的边框样式。
默认值:BorderStyle.Solid
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+ | 设置元素的边框宽度,不支持百分比。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+ | 设置元素的边框颜色。
默认值:Color.Black
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+ | 设置元素的边框圆角半径,不支持百分比。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## EdgeWidths9+对象说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index f56a0c97957064edf50c2f702a1a2f3bbea8c3a9..d4161f28b1303642db2c77ce388c230154a8acd6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -11,7 +11,7 @@ id为组件的唯一标识,在整个应用内唯一。本模块提供组件标 | 名称 | 参数说明 | 描述 | | -----| -------- | ----------------------------- | -| id | string | 组件的唯一标识,唯一性由使用者保证。
默认值:'' | +| id | string | 组件的唯一标识,唯一性由使用者保证。
默认值:''
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 接口 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md index 794627c66f84c4aa409cc521c13fc25326bb6803..7bf82a4ed78ec0ae71b87cb093ebf782057d77e7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md @@ -10,9 +10,9 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| ------- | ------- | ---------------------------------------- | -| enabled | boolean | 值为true表示组件可交互,响应点击等操作。
值为false表示组件不可交互,不响应点击等操作。
默认值:true | +| 名称 | 参数类型 | 描述 | +| ------- | -------- | ------------------------------------------------------------ | +| enabled | boolean | 值为true表示组件可交互,响应点击等操作。
值为false表示组件不可交互,不响应点击等操作。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index 176b1d4b04e4ba33d3adca9b8d309f2d3da6c7b8..e01fba5ea85912d2e78a357edc0ee7d7ff3b6bbf 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -8,12 +8,12 @@ ## 属性 -| 名称 | 参数说明 | 描述 | -| ---------- | ---------------------------------------- | ---------------------------------------- | -| flexBasis | number \| string | 设置组件在父容器主轴方向上的基准尺寸。
默认值:'auto'(表示组件在主轴方向上的基准尺寸为组件原本的大小)。
不支持百分比设置。 | -| flexGrow | number | 设置父容器的剩余空间分配给此属性所在组件的比例。
默认值:0 | -| flexShrink | number | 设置父容器压缩尺寸分配给此属性所在组件的比例。
父容器为Row、Column时,默认值:0
父容器为flex时,默认值:1 | -| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex布局容器中的alignItems设置。
默认值:ItemAlign.Auto | +| 名称 | 参数说明 | 描述 | +| ---------- | ------------------------------------------- | ------------------------------------------------------------ | +| flexBasis | number \| string | 设置组件在父容器主轴方向上的基准尺寸。
默认值:'auto'(表示组件在主轴方向上的基准尺寸为组件原本的大小)。
不支持百分比设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| flexGrow | number | 设置父容器的剩余空间分配给此属性所在组件的比例。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| flexShrink | number | 设置父容器压缩尺寸分配给此属性所在组件的比例。
父容器为Row、Column时,默认值:0
父容器为flex时,默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex布局容器中的alignItems设置。
默认值:ItemAlign.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md index 0a14af72b6503b0b69acffe09f82e866c0c1e6b8..bd84c5ac35432f3649a2f6c3e7d0365746a1858f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md @@ -12,9 +12,9 @@ | 名称 | 参数类型 | 描述 | | -------------- | -------------------------------------------- | ----------------------------------- | -| linearGradient | {
angle?: number \| string,
direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 线性渐变。
- angle: 线性渐变的起始角度。0点方向顺时针旋转为正向角度。
默认值:180
- direction: 线性渐变的方向,设置angle后不生效。
默认值:GradientDirection.Bottom
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false | -| sweepGradient | {
center: Point,
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 角度渐变。
- center:为角度渐变的中心点,即相对于当前组件左上角的坐标。
- start:角度渐变的起点。
默认值:0
- end:角度渐变的终点。
默认值:0
- rotation: 角度渐变的旋转角度。
默认值:0
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false | -| radialGradient | {
center: Point,
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 径向渐变。
- center:径向渐变的中心点,即相对于当前组件左上角的坐标。
- radius:径向渐变的半径。
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false | +| linearGradient | {
angle?: number \| string,
direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 线性渐变。
- angle: 线性渐变的起始角度。0点方向顺时针旋转为正向角度。
默认值:180
- direction: 线性渐变的方向,设置angle后不生效。
默认值:GradientDirection.Bottom
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| sweepGradient | {
center: Point,
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 角度渐变,仅绘制0-360度范围内的角度,超出时不绘制渐变色,只绘制纯色。
- center:为角度渐变的中心点,即相对于当前组件左上角的坐标。
- start:角度渐变的起点。
默认值:0
- end:角度渐变的终点。
默认值:0
- rotation: 角度渐变的旋转角度。
默认值:0
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| radialGradient | {
center: Point,
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | 径向渐变。
- center:径向渐变的中心点,即相对于当前组件左上角的坐标。
- radius:径向渐变的半径。
- colors: 为渐变的颜色描述。
- repeating: 为渐变的颜色重复着色。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-grid.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-grid.md index a81f4e0390a61127903e9ca41168c6b2e8786c1a..1e65c994d71e3e8b7db3c18b160a58aedc6a3374 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-grid.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-grid.md @@ -12,8 +12,8 @@ | 名称 | 参数类型 | 描述 | | ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| useSizeType | {
xs?: number \| { span: number, offset: number },
sm?: number \| { span: number, offset: number },
md?: number \| { span: number, offset: number },
lg?: number \| { span: number, offset: number }
} | 设置在特定设备宽度类型下的占用列数和偏移列数,span: 占用列数; offset: 偏移列数。
当值为number类型时,仅设置列数, 当格式如{"span": 1, "offset": 0}时,指同时设置占用列数与偏移列数。
- xs: 指设备宽度类型为SizeType.XS时的占用列数和偏移列数。
- sm: 指设备宽度类型为SizeType.SM时的占用列数和偏移列数。
- md: 指设备宽度类型为SizeType.MD时的占用列数和偏移列数。
- lg: 指设备宽度类型为SizeType.LG时的占用列数和偏移列数。 | -| gridSpan | number | 默认占用列数,指useSizeType属性没有设置对应尺寸的列数(span)时,占用的栅格列数。
**说明:**
设置了栅格span属性,组件的宽度由栅格布局决定。
默认值:1 | +| useSizeType(deprecated) | {
xs?: number \| { span: number, offset: number },
sm?: number \| { span: number, offset: number },
md?: number \| { span: number, offset: number },
lg?: number \| { span: number, offset: number }
} | 设置在特定设备宽度类型下的占用列数和偏移列数,span: 占用列数; offset: 偏移列数。
当值为number类型时,仅设置列数, 当格式如{"span": 1, "offset": 0}时,指同时设置占用列数与偏移列数。
- xs: 指设备宽度类型为SizeType.XS时的占用列数和偏移列数。
- sm: 指设备宽度类型为SizeType.SM时的占用列数和偏移列数。
- md: 指设备宽度类型为SizeType.MD时的占用列数和偏移列数。
- lg: 指设备宽度类型为SizeType.LG时的占用列数和偏移列数。
该属性从API version 9开始废弃,推荐使用新组件[GridCol](ts-container-gridcol.md)、[GridRow](ts-container-gridrow.md)。 | +| gridSpan | number | 默认占用列数,指useSizeType属性没有设置对应尺寸的列数(span)时,占用的栅格列数。
**说明:**
设置了栅格span属性,组件的宽度由栅格布局决定。
默认值:1 | | gridOffset | number | 默认偏移列数,指useSizeType属性没有设置对应尺寸的偏移(offset)时, 当前组件沿着父组件Start方向,偏移的列数,也就是当前组件位于第n列。
**说明:**
- 配置该属性后,当前组件在父组件水平方向的布局不再跟随父组件原有的布局方式,而是沿着父组件的Start方向偏移一定位移。
- 偏移位移 = (列宽 + 间距)\* 列数。
- 设置了偏移(gridOffset)的组件之后的兄弟组件会根据该组件进行相对布局,类似相对布局。
默认值:0 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index be65bcfe889e696a038fc993470e97c6f8897a56..36fbde66b13830a33a59b8811ee733531d583cb7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -12,22 +12,24 @@ | 名称 | 参数类型 | 默认值 | 描述 | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | -| blur | number | - | 为当前组件添加内容模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。 | -| backdropBlur | number | - | 为当前组件添加背景模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。 | -| shadow | [ShadowOptions](#shadowoptions对象说明) \| [ShadowStyle](#shadowstyle10枚举说明) | - | 为当前组件添加阴影效果。
入参类型为ShadowOptions时,可以指定模糊半径、阴影的颜色、X轴和Y轴的偏移量。
入参类型为ShadowStyle时,可指定不同阴影样式。| -| grayscale | number | 0.0 | 为当前组件添加灰度效果。值定义为灰度转换的比例,入参1.0则完全转为灰度图像,入参则0.0图像无变化,入参在0.0和1.0之间时,效果呈线性变化。(百分比) | -| brightness | number | 1.0 | 为当前组件添加高光效果,入参为高光比例,值为1时没有效果,小于1时亮度变暗,0为全黑;大于1时亮度增加,数值越大亮度越大。 | -| saturate | number | 1.0 | 为当前组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大;小于1时消色成分越大,饱和度越小。(百分比) | -| contrast | number | 1.0 | 为当前组件添加对比度效果,入参为对比度的值,值为1时,显示原图;大于1时,值越大对比度越高,图像越清晰醒目;小于1时,值越小对比度越低;当对比度为0时,图像变为全灰。(百分比) | -| invert | number | 0 | 反转输入的图像。入参为图像反转的比例。值为1时完全反转。值为0则图像无变化。(百分比) | -| sepia | number | 0 | 将图像转换为深褐色。入参为图像反转的比例。值为1则完全是深褐色的,值为0图像无变化。 (百分比) | -| hueRotate | number \| string | '0deg' | 色相旋转效果,输入参数为旋转角度。 | -| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | 为当前组件添加颜色叠加效果,入参为叠加的颜色。 | +| blur | number | - | 为当前组件添加内容模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backdropBlur | number | - | 为当前组件添加背景模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| shadow | [ShadowOptions](#shadowoptions对象说明) \| [ShadowStyle](#shadowstyle10枚举说明) | - | 为当前组件添加阴影效果。
入参类型为ShadowOptions时,可以指定模糊半径、阴影的颜色、X轴和Y轴的偏移量。
入参类型为ShadowStyle时,可指定不同阴影样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
ArkTS卡片上不支持参数为 [ShadowStyle](#shadowstyle10枚举说明)类型。 | +| grayscale | number | 0.0 | 为当前组件添加灰度效果。值定义为灰度转换的比例,入参1.0则完全转为灰度图像,入参则0.0图像无变化,入参在0.0和1.0之间时,效果呈线性变化。(百分比)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| brightness | number | 1.0 | 为当前组件添加高光效果,入参为高光比例,值为1时没有效果,小于1时亮度变暗,0为全黑;大于1时亮度增加,数值越大亮度越大。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| saturate | number | 1.0 | 为当前组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大;小于1时消色成分越大,饱和度越小。(百分比)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| contrast | number | 1.0 | 为当前组件添加对比度效果,入参为对比度的值,值为1时,显示原图;大于1时,值越大对比度越高,图像越清晰醒目;小于1时,值越小对比度越低;当对比度为0时,图像变为全灰。(百分比)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| invert | number | 0 | 反转输入的图像。入参为图像反转的比例。值为1时完全反转。值为0则图像无变化。(百分比)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| sepia | number | 0 | 将图像转换为深褐色。入参为图像反转的比例。值为1则完全是深褐色的,值为0图像无变化。 (百分比)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| hueRotate | number \| string | '0deg' | 色相旋转效果,输入参数为旋转角度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | 为当前组件添加颜色叠加效果,入参为叠加的颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## ShadowOptions对象说明 阴影属性集合,用于设置阴影的模糊半径、阴影的颜色、X轴和Y轴的偏移量。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | --------------- | | radius | number \| [Resource](ts-types.md#resource) | 是 | 阴影模糊半径。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index 5fb5468e9a67be8d63c19ce5f20c7057a542527f..7049c1352559952f5c9e3625ae5fcdc001d894e0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -9,10 +9,10 @@ ## 属性 -| 名称 | 参数说明 | 描述 | -| --------------- | ------ | ---------------------------------------- | -| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。 | -| displayPriority | number | 设置当前组件在布局容器中显示的优先级,当父容器空间不足时,低优先级的组件会被隐藏。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
**说明:**
仅在Row/Column/Flex(单行)容器组件中生效。 | +| 名称 | 参数说明 | 描述 | +| --------------- | -------- | ------------------------------------------------------------ | +| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| displayPriority | number | 设置当前组件在布局容器中显示的优先级,当父容器空间不足时,低优先级的组件会被隐藏。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex(单行)容器组件中生效。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 2cd02ad07fdec4be3adf55264fb101d2379e4420..d48f2173dba569da02985ffbe9ebcac2de6790c1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -12,12 +12,12 @@ | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | 设置元素内容在元素绘制区域内的对齐方式。
默认值:Alignment.Center | -| direction | [Direction](ts-appendix-enums.md#direction) | 设置元素水平方向的布局。
默认值:Direction.Auto | -| position | [Position](ts-types.md#position8) | 绝对定位,设置元素左上角相对于父容器左上角偏移位置。在布局容器中,设置该属性不影响父容器布局,仅在绘制时进行位置调整。 | -| markAnchor | [Position](ts-types.md#position8) | 设置元素在位置定位时的锚点,以元素左上角作为基准点进行偏移。通常配合position和offset属性使用,单独使用时,效果类似offset
默认值:
{
x: 0,
y: 0
} | -| offset | [Position](ts-types.md#position8) | 相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。
默认值:
{
x: 0,
y: 0
} | -| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | 指定相对容器的对齐规则,仅当父容器为[RelativeContainer](ts-container-relativecontainer.md)时生效。
- left:设置左对齐参数。
- right:设置右对齐参数。
- middle:设置中间对齐的参数。
- top:设置顶部对齐的参数。
- bottom:设置底部对齐的参数。
- center:设置中心对齐的参数。
**说明:**
- anchor:设置作为锚点的组件的id值。
- align:设置相对于锚点组件的对齐方式。 | +| align | [Alignment](ts-appendix-enums.md#alignment) | 设置元素内容在元素绘制区域内的对齐方式。
默认值:Alignment.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| direction | [Direction](ts-appendix-enums.md#direction) | 设置元素水平方向的布局。
默认值:Direction.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| position | [Position](ts-types.md#position8) | 绝对定位,设置元素左上角相对于父容器左上角偏移位置。在布局容器中,设置该属性不影响父容器布局,仅在绘制时进行位置调整。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| markAnchor | [Position](ts-types.md#position8) | 设置元素在位置定位时的锚点,以元素左上角作为基准点进行偏移。通常配合position和offset属性使用,单独使用时,效果类似offset
默认值:
{
x: 0,
y: 0
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| offset | [Position](ts-types.md#position8) | 相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。
默认值:
{
x: 0,
y: 0
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| 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) }
} | 指定相对容器的对齐规则,仅当父容器为[RelativeContainer](ts-container-relativecontainer.md)时生效。
- left:设置左对齐参数。
- right:设置右对齐参数。
- middle:设置中间对齐的参数。
- top:设置顶部对齐的参数。
- bottom:设置底部对齐的参数。
- center:设置中心对齐的参数。
该接口支持在ArkTS卡片中使用。
**说明:**
- anchor:设置作为锚点的组件的id值。
- align:设置相对于锚点组件的对齐方式。 | ## 示例 @@ -41,6 +41,7 @@ struct PositionExample1 { Text('Bottom end') .align(Alignment.BottomEnd) + .textAlign(TextAlign.End) .height(50) .width('90%') .fontSize(16) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md index e0fa17c2e61bab1acc534cb900ab81883deaba8b..5d852b468abaad2b32a99ca16a579add7d73c988 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md @@ -10,9 +10,9 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| ------- | ---------------------------------------- | ---------------------------------------- | -| opacity | number \| [Resource](ts-types.md#resource) | 元素的不透明度,取值范围为0到1,1表示不透明,0表示完全透明, 达到隐藏组件效果,但是在布局中占位。 默认值:1
**说明:**
子组件会继承父组件的透明度,并与自身的透明度属性叠加。如:父组件透明度为0.1,子组件设置透明度为0.8,则子组件实际透明度为0.1*0.8=0.08。| +| 名称 | 参数类型 | 描述 | +| ------- | ---------------------------------------------------- | ------------------------------------------------------------ | +| opacity | number \| [Resource](ts-types.md#resource) | 元素的不透明度,取值范围为0到1,1表示不透明,0表示完全透明, 达到隐藏组件效果,但是在布局中占位。 默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
子组件会继承父组件的透明度,并与自身的透明度属性叠加。如:父组件透明度为0.1,子组件设置透明度为0.8,则子组件实际透明度为0.1*0.8=0.08。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 153cb7f34463052a855476f22fda8b76ddbb2233..95da98af8a3393950bb33a6a621671cacd1f33a4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -10,7 +10,7 @@ | 名称 | 参数类型 | 默认值 | 描述 | | -------- | -------- | -------- | -------- | -| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment), 
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | 在当前组件上,增加遮罩文本。
value: 遮罩文本内容。
options: 文本定位,align设置文本相对于组件的方位,[offset](ts-universal-attributes-location.md)为文本基于自身左上角的偏移量。文本默认处于组件左上角。
两者都设置时效果重叠,文本相对于组件方位定位后再基于当前位置文本的左上角进行偏移。 | +| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment), 
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | 在当前组件上,增加遮罩文本。
value: 遮罩文本内容。
options: 文本定位,align设置文本相对于组件的方位,[offset](ts-universal-attributes-location.md)为文本基于自身左上角的偏移量。文本默认处于组件左上角。
两者都设置时效果重叠,文本相对于组件方位定位后再基于当前位置文本的左上角进行偏移。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md index eebd642335745d02b1f2ed25dd864901462278e7..cefbbec1b1992760edf17069900d024c4ba9a32c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md @@ -11,10 +11,12 @@ | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| stateStyles | StateStyles | 设置组件不同状态的样式。 | +| stateStyles | StateStyles | 设置组件不同状态的样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## StateStyles接口说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 必填 | 描述 | | -------- | -------- | -------- | -------- | | normal | ()=>void | 否 | 组件无状态时的样式。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md index 00fe83401f13a4feded827a272cdba5dad75f4a9..d7c6f070afe88b8046b38870ef2e7176491661d1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md @@ -12,8 +12,8 @@ | 名称 | 参数类型 | 描述 | | -----| ------------------------------------------ | ------------------------------------ | -| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | 参数为相应类型的组件,按指定的形状对当前组件进行裁剪;参数为boolean类型时,设置是否按照父容器边缘轮廓进行裁剪。
默认值:false | -| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | 在当前组件上加上指定形状的遮罩。 | +| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | 参数为相应类型的组件,按指定的形状对当前组件进行裁剪;参数为boolean类型时,设置是否按照父容器边缘轮廓进行裁剪。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | 在当前组件上加上指定形状的遮罩。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index a4e65b50d26c7e4188f3ffc9409c6abf3a1265c5..c091d5e51f1954fe78e4750bf8401dc797163d5e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -10,15 +10,15 @@ ## 属性 -| 名称 | 参数说明 | 描述 | -| -------------- | ---------------------------------------- | ---------------------------------------- | -| width | [Length](ts-types.md#length) | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。若子组件的宽大于父组件的宽,则会画出父组件的范围。 | -| height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。 | -| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | 设置高宽尺寸。 | -| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | 设置内边距属性。
参数为Length类型时,四个方向内边距同时生效。
默认值:0
padding设置百分比时,上下左右内边距均以父容器的width作为基础值。 | -| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | 设置外边距属性。
参数为Length类型时,四个方向外边距同时生效。
默认值:0
margin设置百分比时,上下左右外边距均以父容器的width作为基础值。| -| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。若设置的minWidth大于maxWidth,则minWidth生效,minHeight与maxHeight同理。
默认值:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
} | -| layoutWeight | number \| string | 父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。
**说明:**
仅在Row/Column/Flex布局中生效。| +| 名称 | 参数说明 | 描述 | +| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| width | [Length](ts-types.md#length) | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。若子组件的宽大于父组件的宽,则会画出父组件的范围。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | 设置高宽尺寸。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | 设置内边距属性。
参数为Length类型时,四个方向内边距同时生效。
默认值:0
padding设置百分比时,上下左右内边距均以父容器的width作为基础值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | 设置外边距属性。
参数为Length类型时,四个方向外边距同时生效。
默认值:0
margin设置百分比时,上下左右外边距均以父容器的width作为基础值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。若设置的minWidth大于maxWidth,则minWidth生效,minHeight与maxHeight同理。
默认值:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| layoutWeight | number \| string | 父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。
**说明:**
仅在Row/Column/Flex布局中生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 5491d40f9dabbf8166d19255f7e1723d23dae0bc..5cb4dcb09c9d2b7ff7c23ede334363329d791044 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -1,6 +1,6 @@ -# 文本样式设置 +# 文本通用属性 -针对包含文本元素的组件,设置文本样式。 +文本通用属性目前只针对包含文本元素的组件,设置文本样式。 > **说明:** > @@ -18,6 +18,8 @@ | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 设置字体样式。
默认值:FontStyle.Normal | | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | 设置文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。
默认值:FontWeight.Normal | | fontFamily | string \| [Resource](ts-types.md#resource) | 设置字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 | +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
} | ## 示例 @@ -58,4 +60,4 @@ struct TextStyleExample { } ``` -![textstyle](figures/textstyle.PNG) +![textstyle](figures/textstyle.png) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md index aa8a4903a08a0394c911ef53a797789add582904..6782a448b7d950d0a2d3eee53ebe50a3f0fcbc54 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md @@ -11,12 +11,15 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| -------------- | --------------------------------------------- | ----------------------------------------- | -| responseRegion | Array<[Rectangle](#rectangle对象说明)> \| [Rectangle](#rectangle对象说明) | 设置一个或多个触摸热区,包括位置和大小。
默认触摸热区为整个组件,默认值:
{
x:0,
y:0,
width:'100%',
height:'100%'
} | +| 名称 | 参数类型 | 描述 | +| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| responseRegion | Array<[Rectangle](#rectangle对象说明)> \| [Rectangle](#rectangle对象说明) | 设置一个或多个触摸热区,包括位置和大小。
默认触摸热区为整个组件,默认值:
{
x:0,
y:0,
width:'100%',
height:'100%'
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## Rectangle对象说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 必填 | 描述 | | ------ | ----------------------------- | -----| -------------------------------- | | x | [Length](ts-types.md#length) | 否 | 触摸点相对于组件左上角的x轴坐标。
默认值:0vp | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md index 2c9869a9dce1c8dc8f81791848d0a7293b516d43..648f16c3e6166c41a15204f6587ba5c4ad162001 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md @@ -11,9 +11,9 @@ | 名称 | 参数类型 | 描述 | | --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | (x, y, z)指定一个矢量,表示旋转轴,正角度为顺时针转动,负角度为逆时针转动,默认值为0,同时可以通过centerX和centerY设置旋转的中心点。
默认值:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
} | -| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | 可以分别设置X轴、Y轴、Z轴的平移距离,距离的正负控制平移的方向。不支持百分比形式的输入。
默认值:
{
x: 0,
y: 0,
z: 0
} | -| scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | 可以分别设置X轴、Y轴、Z轴的缩放比例,默认值为1,同时可以通过centerX和centerY设置缩放的中心点。
默认值:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
} | +| rotate | {
x?: number,
y?: number,
z?: number,
angle: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | (x, y, z)指定一个矢量,表示旋转轴,正角度为顺时针转动,负角度为逆时针转动,默认值为0,同时可以通过centerX和centerY设置旋转的中心点。
默认值:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | 可以分别设置X轴、Y轴、Z轴的平移距离,距离的正负控制平移的方向。不支持百分比形式的输入。
默认值:
{
x: 0,
y: 0,
z: 0
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | 可以分别设置X轴、Y轴、Z轴的缩放比例,默认值为1,同时可以通过centerX和centerY设置缩放的中心点。
默认值:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | transform | [Matrix4Transit](../apis/js-apis-matrix4.md) | 设置当前组件的变换矩阵。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md index acb3efd2c503f4f5cc370d2e53c651103b38add4..972a0141578dc2e8863fb1453fb96570c0129ad3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md @@ -10,7 +10,7 @@ | 名称 | 参数类型 | 描述 | | ---------- | ---------------------------- | ------------------------------------------ | -| visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../quick-start/arkts-rendering-control.md#条件渲染)代替。
默认值:Visibility.Visible| +| visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../quick-start/arkts-rendering-control.md#条件渲染)代替。
默认值:Visibility.Visible
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md index 60f6b667a8060ce86195496e469633dcf958602d..672db61316eb41f45aacc885faa821b8db9996f7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md @@ -12,7 +12,7 @@ | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| zIndex | number | 同一容器中兄弟组件显示层级关系。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。 | +| zIndex | number | 同一容器中兄弟组件显示层级关系。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-click.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-click.md index 33f2d964f4432eecd591abb1d4d0992328f2b0ff..2e84bd5c8327546e79e4c4f3150931f3e2c8d857 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-click.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-click.md @@ -11,9 +11,12 @@ | 名称 | 支持冒泡 | 功能描述 | | ---------------------------------------- | ---- | --------------------------------- | -| onClick(event: (event?: ClickEvent) => void) | 否 | 点击动作触发该回调,event返回值见ClickEvent对象说明。 | +| onClick(event: (event?: ClickEvent) => void) | 否 | 点击动作触发该回调,event返回值见ClickEvent对象说明。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## ClickEvent对象说明 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 类型 | 描述 | | ------------------- | ------------------------------------ | -------------------------------------------------------- | | screenX | number | 点击位置相对于应用窗口左上角的X坐标。 | @@ -26,6 +29,8 @@ ## EventTarget8+对象说明 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 名称 | 参数类型 | 描述 | | ---- | ------------------------- | ---------- | | area | [Area](ts-types.md#area8) | 目标元素的区域信息。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md index a84c69fc4393a1065f9678c1193406ebfaa1cc16..e0e2c14eb81d9a56f82e7f23b32b251eedae6493 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md @@ -9,10 +9,10 @@ ## 事件 -| 名称 | 支持冒泡 | 功能描述 | -| ------------------------------------------------ | -------- | -------------------------- | -| onAppear(event: () => void) | 否 | 组件挂载显示时触发此回调。 | -| onDisAppear(event: () => void) | 否 | 组件卸载消失时触发此回调。 | +| 名称 | 支持冒泡 | 功能描述 | +| ------------------------------------------------ | -------- | ------------------------------------------------------------ | +| onAppear(event: () => void) | 否 | 组件挂载显示时触发此回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onDisAppear(event: () => void) | 否 | 组件卸载消失时触发此回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md index 7e61c5e73bdf16d7bccf4cecdd4cd9045ed69a86..6f6b2cb855d65b2d2820613ae9273c74f763ce28 100644 --- a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md +++ b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md @@ -27,7 +27,7 @@ - 资源管理 - [I18n错误码](errorcode-i18n.md) - [资源管理错误码](errorcode-resource-manager.md) -- 资源调度 +- 后台任务 - [backgroundTaskManager错误码](errorcode-backgroundTaskMgr.md) - [DeviceUsageStatistics错误码](errorcode-DeviceUsageStatistics.md) - [reminderAgentManager错误码](errorcode-reminderAgentManager.md) diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md b/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md index bcea1a8c6c40325a5878a3c8aa603367b37de806..449647cc0ccb75ccf12adac41b9ef7eabba7caac 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md @@ -3,7 +3,7 @@ ## 1500001 want中Action为空 **错误信息** -> Want action is null +> The action field in the want parameter is null. **错误描述** > 发送事件的`want`中的`Action`属性为空时系统会产生此错误码。 @@ -17,7 +17,7 @@ ## 1500002 沙箱应用无法发送公共事件 **错误信息** -> sandbox application can not send common event +> A sandbox application cannot send common events. **错误描述** > 沙箱应用无法发送公共事件。 @@ -31,7 +31,7 @@ ## 1500003 事件发送频率过高 **错误信息** -> common event send frequency too high +> Too many common events are send in a short period of time. **错误描述** > 应用发送事件过于频繁。 @@ -45,7 +45,7 @@ ## 1500004 无法发送系统公共事件 **错误信息** -> not System services or System app +> A third-party application cannot send system common events. **错误描述** > 当前应用无法发送系统公共事件。 @@ -59,7 +59,7 @@ ## 1500005 未找到订阅者 **错误信息** -> subscriber can not found +> The subscriber is not found. **错误描述** > 找不到订阅者。 @@ -73,7 +73,7 @@ ## 1500006 无效userId **错误信息** -> userId is invalid +> Invalid userId. **错误描述** > 无效的userId。 @@ -87,7 +87,7 @@ ## 1500007 IPC请求发送失败 **错误信息** -> message send error +> Failed to send the message. **错误描述** > `IPC`发送请求失败。 @@ -101,7 +101,7 @@ ## 1500008 读取数据失败 **错误信息** -> CEMS error +> Failed to read the data. **错误描述** > 服务端发生错误。 @@ -112,10 +112,10 @@ **处理步骤** > 稍后重新尝试。 -## 1500009 system error +## 1500009 系统错误 **错误信息** -> system error +> System error. **错误描述** > 处理业务时系统发生异常,如获取系统当前时间失败。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-bluetoothManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-bluetoothManager.md new file mode 100644 index 0000000000000000000000000000000000000000..cbeb39e34a20ae984a62c6f55373c63eb26371d4 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-bluetoothManager.md @@ -0,0 +1,128 @@ +# 蓝牙服务子系统错误码 + +## 2900001 + +**错误信息** + +Service stopped. + +**错误描述** + +蓝牙服务已停止,蓝牙服务相关的接口无法调用。 + +**可能原因** + +蓝牙服务启动异常。 + +**处理步骤** + +重新执行打开或关闭蓝牙。 + +## 2900003 + +**错误信息** + +Bluetooth switch is off. + +**错误描述** + +蓝牙开关已关闭。 + +**可能原因** + +蓝牙开关已关闭。 + +**处理步骤** + +重新执行打开蓝牙开关。 + +## 2900004 + +**错误信息** + +Profile is not supported. + +**错误描述** + +配置文件是不支持的。 + +**可能原因** + +该配置文件在当前设备环境不支持。 + +**处理步骤** + +检查设备是否支持该配置文件功能,若不支持则停止调用。 + +## 2900099 + +**错误信息** + +Operation failed. + +**错误描述** + +操作失败。 + +**可能原因** + +该配置文件在当前设备环境不支持。 + +**处理步骤** + +请重试该操作。 + +## 2901000 + +**错误信息** + +Read forbidden. + +**错误描述** + +禁止读操作。 + +**可能原因** + +无读操作权限。 + +**处理步骤** + +检查是否有读操作权限。 + +## 2901001 + +**错误信息** + +Write forbidden. + +**错误描述** + +禁止写操作。 + +**可能原因** + +无写操作权限。 + +**处理步骤** + +检查是否有写操作权限。 + +## 2901054 + +**错误信息** + +IO error. + +**错误描述** + +IO传输失败。 + +**可能原因** + +IO传输异常,造成失败。 + +**处理步骤** + +请重试该操作。 + diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md b/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md index b8df64665eb74f2427257730932c8b8e2039ac39..1df877821072768b36688be89a0a26e22cf9c5c9 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md @@ -1,397 +1,513 @@ -# 包管理子系统通用错误码 - -## 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. 检查moduleName拼写是否正确。 -2. 确认对应的应用是否安装该模块。 - -## 17700003 指定的abilityName不存在 - -**错误信息**
-The specified ability name is not found. - -**错误描述**
-调用查询等接口时,传入的abilityName不存在。 - -**可能原因**
-1. 输入的abilityName有误。 -2. 系统中对应的应用不存在该abilityName对应的ability。 - -**处理步骤**
-1. 检查abilityName拼写是否正确。 -2. 确认对应的应用是否存在该abilityName对应的ability。 - -## 17700004 指定的用户不存在 - -**错误信息**
-The specified user ID is not found. - -**错误描述**
-调用与用户相关接口时,传入的用户不存在。 - -**可能原因**
-1. 输入的用户名有误。 -2. 系统中没有该用户。 - -**处理步骤**
-1. 检查用户名拼写是否正确。 -2. 确认系统中存在该用户。 - -## 17700005 指定的appId为空字符串 - -**错误信息**
-The specified app ID is empty string. - -**错误描述**
-调用appControl模块中的相关接口时,传入的appId为空字符串。 - -**可能原因**
-传入的appId为空字符串。 - -**处理步骤**
-检查appId是否为空字符串。 - -## 17700006 查询的权限不存在 - -**错误信息**
-The specified permission is not found. - -**错误描述**
-调用bundleManager模块中的getPermissionDef接口时,传入的权限不存在。 - -**可能原因**
-1. 传入的permission名称拼写有误。 -2. 系统中不存在对应的权限。 - -**处理步骤**
-1. 检查permission拼写是否正确。 -2. 确认系统中是否有该权限。 - -## 17700007 输入的设备Id有误 - -**错误信息**
-The specified device ID is not found. - -**错误描述**
-调用distributedBundle模块相关接口时,传入的设备id有误。 - -**可能原因**
-1. 传入的deviceId拼写有误。 -2. deviceId不存在。 - -**处理步骤**
-1. 检查deviceId拼写是否正确。 -2. 确认deviceId是否存在。 - -## 17700010 文件解析失败导致应用安装失败 - -**错误信息**
-Failed to install the HAP because the HAP fails to be parsed. - -**错误描述**
-调用installer模块中的install接口时,传入的HAP解析失败。 - -**可能原因**
-1. HAP的格式不是zip格式。 -2. HAP的配置文件不满足json格式。 -3. HAP的配置文件缺少必要的字段。 - -**处理步骤**
-1. 确认hap的格式是zip。 -2. 确认hap的配置文件满足[配置文件json格式](../../quick-start/application-configuration-file-overview-stage.md)。 -3. 检查DevEco Studio编译hap时是否有错误提示,缺省字段时会有相应的报错。 - -## 17700011 签名校验失败导致应用安装失败 - -**错误信息**
-Failed to install the HAP because the HAP signature fails to be verified. - -**错误描述**
-调用installer模块中的install接口时,签名校验失败导致应用安装失败。 - -**可能原因**
- -1. HAP没有签名。 -2. hap签名信息来源不可靠。 -3. 升级的HAP与已安装的HAP签名信息不一致。 -4. 多个hap的签名信息不一致。 - -**处理步骤**
-1. 确认hap包是否签名成功。 -2. 确认hap包的签名证书是从应用市场申请。 -3. 确认多个hap包签名时使用的证书相同。 -4. 确认升级的ha包p签名证书与已安装的hap包相同。 - -## 17700012 安装包路径无效或者文件过大导致应用安装失败 - -**错误信息**
-Failed to install the HAP because the HAP path is invalid or the HAP is too large. - -**错误描述**
-调用installer模块中的install接口时,安装包路径无效或者文件过大导致应用安装失败。 - -**可能原因**
-1. 输入错误,HAP的文件路径不存在。 -2. HAP的路径无法访问。 -3. HAP的大小超过最大限制4G。 - -**处理步骤**
-1. 确认hap是否存在。 -2. 查看hap的可执行权限,是否可读。 -3. 查看HAP的大小是否超过4G。 - -## 17700015 多个HAP配置信息不同导致应用安装失败 - -**错误信息**
-Failed to install the HAPs because they have different configuration information. - -**错误描述**
-调用installer模块中的install接口时,多个HAP配置信息不同导致应用安装失败。 - -**可能原因**
-多个hap包中配置文件中app标签下面的字段信息不一致。 - -**处理步骤**
-确认多个HAP中配置文件app下面的字段是否一致。 - -## 17700016 系统磁盘空间不足导致应用安装失败 - -**错误信息**
-Failed to install the HAP because of insufficient system disk space. - -**错误描述**
-调用installer模块中的install接口时,系统磁盘空间不足导致应用安装失败。 - -**可能原因**
-系统空间不足。 - -**处理步骤**
-确认系统是否有足够的空间。 - -## 17700017 新安装的应用版本号低于已安装的版本号导致应用安装失败 - -**错误信息**
-Failed to install the HAP since the version of the HAP to install is too early. - -**错误描述**
-调用installer模块中的install接口时,新安装的应用版本号低于已安装的版本号导致应用安装失败。 - -**可能原因**
-新安装的应用版本号低于已安装的版本号。 - -**处理步骤**
-确认新安装的应用版本号是否不低于已安装的同应用版本号。 - -## 17700020 预置应用无法卸载 - -**错误信息**
-The preinstalled app cannot be uninstalled. - -**错误描述**
-调用installer模块中的uninstall接口卸载预置应用时,无法卸载。 - -**可能原因**
-1. 传入的bundleName拼写有误。 -2. 对应的预置应用无法卸载。 - -**处理步骤**
-1. 确认bundleName是否拼写正确。 -1. 确认对应的预置应用是否可卸载。 - -## 17700021 指定的uid无效 - -**错误信息**
-The specified uid is invalid. - -**错误描述**
-调用bundleManager模块中的getBundleNameByUid接口时,指定的uid无效。 - -**可能原因**
-1. 传入的uid拼写有误。 -2. 传入的uid在系统中不存在。 - -**处理步骤**
-1. 检查uid的拼写。 -2. 检查系统中是否存在该uid。 - -## 17700022 输入的待解析源文件无效 - -**错误信息**
-The input source file is invalid. - -**错误描述**
-调用bundleManager模块中的getBundleArchiveInfo接口时,传入的HAP路径无效。 - -**可能原因**
-1. 待解析的源文件不存在。 -2. 待解析的源文件不符合zip格式。 - -**处理步骤**
-1. 确认待解析的源文件是否存在。 -2. 确认待解析的源文件符合zip格式。 - -## 17700023 指定的默认应用不存在 - -**错误信息**
-The specified default app does not exist. - -**错误描述**
-调用defaultAppManager模块中的getDefaultApplication接口时,指定的默认应用不存在。 - -**可能原因**
-设备没有设置对应的默认应用。 - -**处理步骤**
-确认设备是否设置了对应的默认应用。 - -## 17700024 没有相应的配置文件 - -**错误信息**
-Failed to get the profile because there is no profile in the HAP. - -**错误描述**
-调用查询profile文件的相关接口时,没有相应的配置文件。 - -**可能原因**
-1. 输入的metadata name在配置文件中不存在。 -2. 配置文件的内容不是json格式。 - -**处理步骤**
-1. 确认要查询的ability或者extensionAbility中的metadata name是否存在。 -2. 确认指定查询的profile文件的内容是否为json格式。 - -## 17700025 输入的type无效 - -**错误信息**
-The specified type is invalid. - -**错误描述**
-调用defaultAppManager模块的相关接口时,输入的type无效。 - -**可能原因**
-1. 输入的type拼写有误。 -2. 输入的type不存在。 - -**处理步骤**
-1. 确认输入的type是否拼写正确。 -2. 确认输入的type是否存在。 - -## 17700026 指定应用被禁用 - -**错误信息**
-The specified bundle is disabled. - -**错误描述**
-当调用查询应用的相关信息接口时,指定应用被禁用。 - -**可能原因**
-设备上对应的应用已经被禁用,无法查询。 - -**处理步骤**
-确认设备上对应的应用是否被禁用。 - -## 17700027 分布式服务未启动 - -**错误信息**
-The distributed service is not running. - -**错误描述**
-当调用distributedBundle模块的相关接口时,分布式服务未启动。 - -**可能原因**
-设备未组网。 - -**处理步骤**
-确认设备是否组网成功。 -## 17700028 输入的ability与type不匹配 - -**错误信息**
-The ability does not match the type. - -**错误描述**
-当调用defaultAppManager模块中的setDefaultApplication接口时,输入的ability与type不匹配。 - -**可能原因**
-输入的ability和type拼写有误。 - -**处理步骤**
-确认输入的ability和type拼写是否正确。 - -## 17700029 指定的ability被禁用 - -**错误信息**
-The specified ability is disabled. - -**错误描述**
-当调用查询ability相关信息的接口时,指定的ability被禁用。 - -**可能原因**
-指定的ability被禁用。 - -**处理步骤**
-确认指定的ability是否被禁用,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息。 - -## 17700030 指定的应用不支持清除缓存文件 - -**错误信息**
-The specified bundle does not support clearing of cache files. - -**错误描述**
-当调用bundleManager模块中的cleanBundleCacheFiles接口时,指定的应用不支持清除缓存文件。 - -**可能原因**
-指定的应用为系统应用且在签名证书中配置了不能清除数据(AllowAppDataNotCleared)的字段。 - -**处理步骤**
-1.确认指定的应用是否为系统应用,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息,查看isSystemApp是否为true。 -2.确认指定的应用是否配置了能清除缓存(AllowAppDataNotCleared)的字段,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息,查看userDataClearable是否为true。 - -## 17700031 Overlay特性校验失败导致HAP安装失败 - -**错误信息**
-Failed to install the HAP because the overlay check of the HAP is failed. - -**错误描述**
-当安装overlay特征的应用时,指定的应用和待安装的overlay特征应用不为预置应用,或者目标应用/目标module是overlay特征的应用/module。 - -**可能原因**
-1. 使用应用间的overlay特性时,overlay特征应用必须为预置应用。 -2. 使用应用间的overlay特性时,目标应用必须为预置应用。 -3. 使用应用间的overlay特性时,目标应用不能是具有overlay特征的应用 -4. 目标module不能是具有overlay特征的module。 - -**处理步骤**
-1. 检查overlay特征应用是否为预置应用。 -2. 检查目标应用是否为预置应用。 -3. 检查目标应用是否不为overlay特征的应用 -4. 检查目标module是否不为overlay特征的module。 - +# 包管理子系统通用错误码 + +## 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. 检查moduleName拼写是否正确。 +2. 确认对应的应用是否安装该模块。 + +## 17700003 指定的abilityName不存在 + +**错误信息**
+The specified ability name is not found. + +**错误描述**
+调用查询等接口时,传入的abilityName不存在。 + +**可能原因**
+1. 输入的abilityName有误。 +2. 系统中对应的应用不存在该abilityName对应的ability。 + +**处理步骤**
+1. 检查abilityName拼写是否正确。 +2. 确认对应的应用是否存在该abilityName对应的ability。 + +## 17700004 指定的用户不存在 + +**错误信息**
+The specified user ID is not found. + +**错误描述**
+调用与用户相关接口时,传入的用户不存在。 + +**可能原因**
+1. 输入的用户名有误。 +2. 系统中没有该用户。 + +**处理步骤**
+1. 检查用户名拼写是否正确。 +2. 确认系统中存在该用户。 + +## 17700005 指定的appId为空字符串 + +**错误信息**
+The specified app ID is empty string. + +**错误描述**
+调用appControl模块中的相关接口时,传入的appId为空字符串。 + +**可能原因**
+传入的appId为空字符串。 + +**处理步骤**
+检查appId是否为空字符串。 + +## 17700006 查询的权限不存在 + +**错误信息**
+The specified permission is not found. + +**错误描述**
+调用bundleManager模块中的getPermissionDef接口时,传入的权限不存在。 + +**可能原因**
+1. 传入的permission名称拼写有误。 +2. 系统中不存在对应的权限。 + +**处理步骤**
+1. 检查permission拼写是否正确。 +2. 确认系统中是否有该权限。 + +## 17700007 输入的设备Id有误 + +**错误信息**
+The specified device ID is not found. + +**错误描述**
+调用distributedBundle模块相关接口时,传入的设备id有误。 + +**可能原因**
+1. 传入的deviceId拼写有误。 +2. deviceId不存在。 + +**处理步骤**
+1. 检查deviceId拼写是否正确。 +2. 确认deviceId是否存在。 + +## 17700010 文件解析失败导致应用安装失败 + +**错误信息**
+Failed to install the HAP because the HAP fails to be parsed. + +**错误描述**
+调用installer模块中的install接口时,传入的HAP解析失败。 + +**可能原因**
+1. HAP的格式不是zip格式。 +2. HAP的配置文件不满足json格式。 +3. HAP的配置文件缺少必要的字段。 + +**处理步骤**
+1. 确认hap的格式是zip。 +2. 确认hap的配置文件满足[配置文件json格式](../../quick-start/application-configuration-file-overview-stage.md)。 +3. 检查DevEco Studio编译hap时是否有错误提示,缺省字段时会有相应的报错。 + +## 17700011 签名校验失败导致应用安装失败 + +**错误信息**
+Failed to install the HAP because the HAP signature fails to be verified. + +**错误描述**
+调用installer模块中的install接口时,签名校验失败导致应用安装失败。 + +**可能原因**
+ +1. HAP没有签名。 +2. hap签名信息来源不可靠。 +3. 升级的HAP与已安装的HAP签名信息不一致。 +4. 多个hap的签名信息不一致。 + +**处理步骤**
+1. 确认hap包是否签名成功。 +2. 确认hap包的签名证书是从应用市场申请。 +3. 确认多个hap包签名时使用的证书相同。 +4. 确认升级的ha包p签名证书与已安装的hap包相同。 + +## 17700012 安装包路径无效或者文件过大导致应用安装失败 + +**错误信息**
+Failed to install the HAP because the HAP path is invalid or the HAP is too large. + +**错误描述**
+调用installer模块中的install接口时,安装包路径无效或者文件过大导致应用安装失败。 + +**可能原因**
+1. 输入错误,HAP的文件路径不存在。 +2. HAP的路径无法访问。 +3. HAP的大小超过最大限制4G。 + +**处理步骤**
+1. 确认hap是否存在。 +2. 查看hap的可执行权限,是否可读。 +3. 查看HAP的大小是否超过4G。 + +## 17700015 多个HAP配置信息不同导致应用安装失败 + +**错误信息**
+Failed to install the HAPs because they have different configuration information. + +**错误描述**
+调用installer模块中的install接口时,多个HAP配置信息不同导致应用安装失败。 + +**可能原因**
+多个hap包中配置文件中app标签下面的字段信息不一致。 + +**处理步骤**
+确认多个HAP中配置文件app下面的字段是否一致。 + +## 17700016 系统磁盘空间不足导致应用安装失败 + +**错误信息**
+Failed to install the HAP because of insufficient system disk space. + +**错误描述**
+调用installer模块中的install接口时,系统磁盘空间不足导致应用安装失败。 + +**可能原因**
+系统空间不足。 + +**处理步骤**
+确认系统是否有足够的空间。 + +## 17700017 新安装的应用版本号低于已安装的版本号导致应用安装失败 + +**错误信息**
+Failed to install the HAP since the version of the HAP to install is too early. + +**错误描述**
+调用installer模块中的install接口时,新安装的应用版本号低于已安装的版本号导致应用安装失败。 + +**可能原因**
+新安装的应用版本号低于已安装的版本号。 + +**处理步骤**
+确认新安装的应用版本号是否不低于已安装的同应用版本号。 + +## 17700018 安装失败,依赖的模块不存在 + +**错误信息**
+Failed to install because the dependent module does not exist. + +**错误描述**
+安装hap或者hsp时,依赖的模块不存在。 + +**可能原因**
+依赖的模块没有安装。 + +**处理步骤**
+先安装依赖的模块。 + +## 17700020 预置应用无法卸载 + +**错误信息**
+The preinstalled app cannot be uninstalled. + +**错误描述**
+调用installer模块中的uninstall接口卸载预置应用时,无法卸载。 + +**可能原因**
+1. 传入的bundleName拼写有误。 +2. 对应的预置应用无法卸载。 + +**处理步骤**
+1. 确认bundleName是否拼写正确。 +1. 确认对应的预置应用是否可卸载。 + +## 17700021 指定的uid无效 + +**错误信息**
+The specified uid is invalid. + +**错误描述**
+调用bundleManager模块中的getBundleNameByUid接口时,指定的uid无效。 + +**可能原因**
+1. 传入的uid拼写有误。 +2. 传入的uid在系统中不存在。 + +**处理步骤**
+1. 检查uid的拼写。 +2. 检查系统中是否存在该uid。 + +## 17700022 输入的待解析源文件无效 + +**错误信息**
+The input source file is invalid. + +**错误描述**
+调用bundleManager模块中的getBundleArchiveInfo接口时,传入的HAP路径无效。 + +**可能原因**
+1. 待解析的源文件不存在。 +2. 待解析的源文件不符合zip格式。 + +**处理步骤**
+1. 确认待解析的源文件是否存在。 +2. 确认待解析的源文件符合zip格式。 + +## 17700023 指定的默认应用不存在 + +**错误信息**
+The specified default app does not exist. + +**错误描述**
+调用defaultAppManager模块中的getDefaultApplication接口时,指定的默认应用不存在。 + +**可能原因**
+设备没有设置对应的默认应用。 + +**处理步骤**
+确认设备是否设置了对应的默认应用。 + +## 17700024 没有相应的配置文件 + +**错误信息**
+Failed to get the profile because there is no profile in the HAP. + +**错误描述**
+调用查询profile文件的相关接口时,没有相应的配置文件。 + +**可能原因**
+1. 输入的metadata name在配置文件中不存在。 +2. 配置文件的内容不是json格式。 + +**处理步骤**
+1. 确认要查询的ability或者extensionAbility中的metadata name是否存在。 +2. 确认指定查询的profile文件的内容是否为json格式。 + +## 17700025 输入的type无效 + +**错误信息**
+The specified type is invalid. + +**错误描述**
+调用defaultAppManager模块的相关接口时,输入的type无效。 + +**可能原因**
+1. 输入的type拼写有误。 +2. 输入的type不存在。 + +**处理步骤**
+1. 确认输入的type是否拼写正确。 +2. 确认输入的type是否存在。 + +## 17700026 指定应用被禁用 + +**错误信息**
+The specified bundle is disabled. + +**错误描述**
+当调用查询应用的相关信息接口时,指定应用被禁用。 + +**可能原因**
+设备上对应的应用已经被禁用,无法查询。 + +**处理步骤**
+确认设备上对应的应用是否被禁用。 + +## 17700027 分布式服务未启动 + +**错误信息**
+The distributed service is not running. + +**错误描述**
+当调用distributedBundle模块的相关接口时,分布式服务未启动。 + +**可能原因**
+设备未组网。 + +**处理步骤**
+确认设备是否组网成功。 +## 17700028 输入的ability与type不匹配 + +**错误信息**
+The ability does not match the type. + +**错误描述**
+当调用defaultAppManager模块中的setDefaultApplication接口时,输入的ability与type不匹配。 + +**可能原因**
+输入的ability和type拼写有误。 + +**处理步骤**
+确认输入的ability和type拼写是否正确。 + +## 17700029 指定的ability被禁用 + +**错误信息**
+The specified ability is disabled. + +**错误描述**
+当调用查询ability相关信息的接口时,指定的ability被禁用。 + +**可能原因**
+指定的ability被禁用。 + +**处理步骤**
+确认指定的ability是否被禁用,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息。 + +## 17700030 指定的应用不支持清除缓存文件 + +**错误信息**
+The specified bundle does not support clearing of cache files. + +**错误描述**
+当调用bundleManager模块中的cleanBundleCacheFiles接口时,指定的应用不支持清除缓存文件。 + +**可能原因**
+指定的应用为系统应用且在签名证书中配置了不能清除数据(AllowAppDataNotCleared)的字段。 + +**处理步骤**
+1.确认指定的应用是否为系统应用,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息,查看isSystemApp是否为true。 +2.确认指定的应用是否配置了能清除缓存(AllowAppDataNotCleared)的字段,可以使用[bm工具命令](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md%23bm%E5%B7%A5%E5%85%B7%E5%91%BD%E4%BB%A4)查询对应的应用信息,查看userDataClearable是否为true。 + +## 17700031 Overlay特性校验失败导致HAP安装失败 + +**错误信息**
+Failed to install the HAP because the overlay check of the HAP is failed. + +**错误描述**
+当安装overlay特征的应用时,指定的应用和待安装的overlay特征应用不为预置应用,或者目标应用/目标module是overlay特征的应用/module。 + +**可能原因**
+1. 使用应用间的overlay特性时,overlay特征应用必须为预置应用。 +2. 使用应用间的overlay特性时,目标应用必须为预置应用。 +3. 使用应用间的overlay特性时,目标应用不能是具有overlay特征的应用 +4. 目标module不能是具有overlay特征的module。 + +**处理步骤**
+1. 检查overlay特征应用是否为预置应用。 +2. 检查目标应用是否为预置应用。 +3. 检查目标应用是否不为overlay特征的应用 +4. 检查目标module是否不为overlay特征的module。 + +## 17700032 指定的应用不包含overlay特征的module + +**错误信息**
+The specified bundle does not contain any overlay module. + +**错误描述**
+查询指定应用中overlay特征module的overlayModuleInfo时, 指定的应用不包含overlay特征module。 + +**可能原因**
+指定的应用不包含overlay特征module。 + +**处理步骤**
+检查指定的应用是否不包含overlay特征module。 + +## 17700033 指定的module不是overlay特征的module + +**错误信息**
+The specified module is not overlay module. + +**错误描述**
+查询指定的overlay特征module的overlayModuleInfo时, 指定的module不是overlay特征module。 + +**可能原因**
+指定的module不是overlay特征的module。 + +**处理步骤**
+检查指定的module是否不为overlay特征的module。 + +## 17700034 指定的module是overlay特征的module + +**错误信息**
+The specified module is overlay module. + +**错误描述**
+查询指定的目标module所关联的overlayModuleInfo时, 指定的module是overlay特征module。 + +**可能原因**
+指定的module是overlay特征的module。 + +**处理步骤**
+检查指定的module是否为overlay特征的module。 + +## 17700035 指定的应用只包含overlay特征的module + +**错误信息**
+The specified bundle is overlay bundle. + +**错误描述**
+查询指定应用的目标module所关联的overlayModuleInfo时, 指定的应用只包含overlay特征的module。 + +**可能原因**
+指定的应用只包含overlay特征的module。 + +**处理步骤**
+检查指定的应用是否只包含overlay特征的module。 + +## 17700036 共享库缺少AllowAppShareLibrary特权导致安装失败 + +**错误信息**
+Failed to install because without allow app shared bundle permission. + +**错误描述**
+共享库未申请配置AllowAppShareLibrary特权,可能存在安全隐私风险,不允许安装。 + +**可能原因**
+发布共享库前,未申请配置AllowAppShareLibrary特权。 + +**处理步骤**
+为共享库申请配置AllowAppShareLibrary特权,重新签名并发布。 + +## 17700037 被卸载的shared library版本被其他应用依赖 + +**错误信息**
+The version of shared bundle is dependent on other applications. + +**错误描述**
+当卸载shared library某一版本时,指定的shared library的版本被其他应用依赖,卸载失败。 + +**可能原因**
+1. 当前卸载的版本是shared library的最高版本,且该shared library被其他应用依赖。 +2. 当前卸载时未指定shared library的版本,会卸载shared library的所有版本,该shared library被其他应用依赖。 + +**处理步骤**
+1. 检查被卸载的shared library是否被其他应用依赖。 +2. 检查被卸载的版本是否为shared library的最高版本。 + +## 17700038 被卸载的shared library不存在 + +**错误信息**
+The specified shared bundle does not exist. + +**错误描述**
+当卸载shared library时,卸载的shared library不存在。 + +**可能原因**
+1. 当前指定卸载的版本不存在与被卸载的shared library中。 +2. 当前指定卸载的shared library不存在与设备中。 + +**处理步骤**
+1. 检查被卸载的shared library是否存在于当前设备中。 +2. 检查被卸载的版本是否存在于被卸载的shared library中。 + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md b/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md index 3ed4da85c694859065392150c442d49fa7dcab10..52d7ea0e205dd965a373e404a3beac3669524f78 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md @@ -4,11 +4,11 @@ **错误信息** -The service is not running or broken. +The service is not started or is faulty. **错误描述** -服务未启动/故障。 +服务未启动或者遇到未知错误。 **可能原因** diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md index 5166f78088c57fdce16ca43bc2d54668bdea696e..1e607fb6272dd722c7c4da63bd791c6b9e2706ba 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md @@ -15,6 +15,7 @@ Function is disabled. 应用事件打点功能被关闭了。 **处理步骤** + 调用配置接口开启打点功能。 ```js @@ -41,6 +42,7 @@ Invalid event domain. - 事件领域名称非空且长度不超过32个字符。 **处理步骤** + 传入合法的事件领域名称。 ## 11101002 非法的事件名称 diff --git a/zh-cn/application-dev/reference/syscap-list.md b/zh-cn/application-dev/reference/syscap-list.md index e804c0fe96aee8e94f5987424630bc24d6eda966..33f6ac5f09f4578a8d9b6414b4047854e23303d4 100644 --- a/zh-cn/application-dev/reference/syscap-list.md +++ b/zh-cn/application-dev/reference/syscap-list.md @@ -1394,3 +1394,267 @@ VAID管理服务 | Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | + +## SystemCapability.Security.CertificateManager + +证书管理 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Security.CryptoFramework + +加解密算法库框架-加解密基础能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.Core + +包管理核心业务,包含包信息查询、安装卸载的核心能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.FreeInstall + +包管理提供的免安装特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.Resource + +包管理提供的获取图标和label的特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.DefaultApp + +包管理提供的默认应用管理特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.Launcher + +包管理提供给Launcher的查询特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.SandboxApp + +包管理提供的沙箱应用的特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.QuickFix + +包管理提供的快速修复的特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.AppControl + +包管理提供的拦截特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Graphic.Graphic2D.ColorManager.Core + +富设备广色域管理 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 否 | 是 | 否 | 否 | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +能效资源申请接口 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Multimedia.Media.AVPlayer + +媒体音视频播放引擎能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Multimedia.Media.AVRecorder + +媒体音视频录制引擎能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Security.Cert + +加解密算法库框架-证书能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Security.DataLossPrevention + +数据防泄漏 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 否 | 否 | 否 | 否 | + +## SystemCapability.Communication.NFC.Tag + +NFC标签服务 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 否 | 否 | 否 | 否 | 否 | 否 | 否 | 否 | + +## SystemCapability.Communication.NFC.CardEmulation + +NFC卡模拟服务 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 否 | 否 | 否 | 否 | 否 | 否 | 否 | 否 | + +## SystemCapability.Multimedia.Image.ImageCreator + +图像创建能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Developtools.Syscap + +系统能力编解码 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | + +## SystemCapability.Communication.NetManager.Ethernet + +以太网连接 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 否 | 否 | 否 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Communication.NetManager.NetSharing + +网络共享 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 否 | 是 | 否 | 否 | + +## SystemCapability.Communication.NetManager.MDNS + +mDNS服务 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Communication.NetManager.Vpn + +VPN + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 否 | 是 | 否 | 否 | + +## SystemCapability.XTS.DeviceAttest + +设备证明 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.XTS.DeviceAttestLite + +轻量设备证明 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 否 | 是 | 否 | 否 | 否 | 否 | 是 | 是 | + +## SystemCapability.FileManagement.UserFileManager.Core + +公共用户文件管理基础能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.FileManagement.UserFileManager.DistributedCore + +公共用户文件管理分布式能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.DistributedDataManager.UDMF.Core + +分布式数据管理--统一数据管理框架(UDMF)核心能力 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 否 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.BundleManager.BundleFramework.Overlay + +包管理overlay特性 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Cloud.Push + +推送管理服务 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 是 | 否 | + +## SystemCapability.Multimedia.SystemSound.Core + +系统声音管理,如铃声,通知,闹钟等 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | + +## SystemCapability.Ability.AbilityRuntime.QuickFix + +快速修复 + +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 否 | 是 | 是 | 是 | 是 | 否 | 否 | \ No newline at end of file diff --git a/zh-cn/application-dev/security/app-provision-structure.md b/zh-cn/application-dev/security/app-provision-structure.md index 0bee0fc5f8540d8026f026da84a17e4ef2eba842..f3103bd235e2e1d8ce1740b9f274f47e7d27d4da 100644 --- a/zh-cn/application-dev/security/app-provision-structure.md +++ b/zh-cn/application-dev/security/app-provision-structure.md @@ -62,7 +62,7 @@ HarmonyAppProvision文件示例: ### bundle-info对象内部结构 -**说明:** HarmonyAppProvision文件中的bundle-info对象中bundle-name需要和所签名应用的包名bundleName(config.js/module.json5)保持一致。为了防止同一个HarmonyAppProvision配置文件任意用于不同应用的签名,在应用安装过程中,系统会校验HAP签名信息的bundleName与HAP的配置文件中的bundleName是否一致,如果不一致,HAP无法安装。 +**说明:** HarmonyAppProvision文件中的bundle-info对象中bundle-name需要和所签名应用的包名bundleName(config.json/module.json5)保持一致。为了防止同一个HarmonyAppProvision配置文件任意用于不同应用的签名,在应用安装过程中,系统会校验HAP签名信息的bundleName与HAP的配置文件中的bundleName是否一致,如果不一致,HAP无法安装。 | 属性名称 | 含义 | 数据类型 | 是否必选 | 是否可缺省 | | ------------------------ | ------------------------------- | ------- | -------- | --------- | diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index 1017b119a80ba96bec68f317e138a2b5b8da4efa..793d9cf38adf98302ac0401bf9ff4c1ee784a182 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -647,728 +647,316 @@ HUKS基于密钥会话来操作数据,使用密钥时基于以下流程: ### 加密解密 ```ts /* - * 以下以SM4 128密钥的Callback操作使用为例 + * 以下以AES 128密钥的Callback操作使用为例 */ import huks from '@ohos.security.huks'; +import promptAction from '@ohos.promptAction'; -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let srcKeyAlias = 'sm4_Key'; -let IV = '0000000000000000'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; -let encryptUpdateResult = new Array(); + +let aesKeyAlias = 'test_aesKeyAlias'; let handle; -let updateResult = new Array(); -let finishOutData; +let plainText = '123456'; +let IV = '001122334455'; +let cipherData:Uint8Array; +let plainData:Uint8Array; -/* 集成生成密钥参数集 & 加密参数集 */ -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) + +function Uint8ArrayToString(fileData) { + let dataString = ''; + for (let i = 0; i < fileData.length; i++) { + dataString += String.fromCharCode(fileData[i]); + } + return dataString; } -let propertiesEncrypt = new Array(); -propertiesEncrypt[0] = { +function GetAesGenerateProperties() { + var properties = new Array(); + var index = 0; + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -propertiesEncrypt[1] = { + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 + }; + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + } + return properties; } -propertiesEncrypt[2] = { + +function GetAesEncryptProperties() { + var properties = new Array(); + var index = 0; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -propertiesEncrypt[3] = { + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + } + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -propertiesEncrypt[4] = { + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 + } + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -propertiesEncrypt[5] = { + value: huks.HuksCipherMode.HUKS_MODE_CBC + } + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), -} -let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) + value: StringToUint8Array(IV) + } + return properties; } -/* 修改加密参数集为解密参数集 */ -propertiesEncrypt.splice(1, 1, { +function GetAesDecryptProperties() { + var properties = new Array(); + var index = 0; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 + }; + properties[index++] = { tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -}); -let decryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV) + } + return properties; } -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); +async function GenerateAesKey() { + var genProperties = GetAesGenerateProperties(); + var options = { + properties: genProperties + } + await huks.generateKeyItem(aesKeyAlias, options).then((data) => { + promptAction.showToast({ + message: "成功生成了 一个 AES 密钥", + duration: 2500, + }) + }).catch((err)=>{ + promptAction.showToast({ + message: "密钥生成失败,错误码是: " + err.code + " 错误吗信息: " + err.message, + duration: 6500, + }) + }) +} + +async function EncryptData() { + var encryptProperties = GetAesEncryptProperties(); + var options = { + properties:encryptProperties, + inData: StringToUint8Array(plainText) } - return new Uint8Array(arr); -} + await huks.initSession(aesKeyAlias, options).then((data) => { + handle = data.handle; + }).catch((err)=>{ + promptAction.showToast({ + message: "密钥初始化失败,错误码是: " + err.code + " 错误吗信息: " + err.message, + duration: 6500, + }) + }) + await huks.finishSession(handle, options).then((data) => { + promptAction.showToast({ + message: "加密数据成功, 密文是: " + Uint8ArrayToString(data.outData), + duration: 6500, + }) + cipherData = data.outData + }).catch((err)=>{ + promptAction.showToast({ + message: "加密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message, + duration: 6500, + }) + }) +} + +async function DecryptData() { + var decryptOptions = GetAesDecryptProperties() + var options = { + properties:decryptOptions, + inData: cipherData + } + await huks.initSession(aesKeyAlias, options).then((data) => { + handle = data.handle; + }).catch((err)=>{ + promptAction.showToast({ + message: "密钥初始化失败,错误码是: " + err.code + " 错误吗信息: " + err.message, + duration: 6500, + }) + }) + await huks.finishSession(handle, options).then((data) => { + promptAction.showToast({ + message: "解密成功, 解密的明文是: " + Uint8ArrayToString(data.outData), + duration: 6500, + }) + }).catch((err)=>{ + promptAction.showToast({ + message: "解密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message, + duration: 6500, + }) + }) +} + +async function DeleteKey() { + let emptyOptions = { + properties:[] + } + await huks.deleteKeyItem(aesKeyAlias, emptyOptions).then((data) => { + promptAction.showToast({ + message: "密钥删除成功!", + duration: 6500, + }) + }).catch((err)=>{ + promptAction.showToast({ + message: "密钥删除失败,错误码是: " + err.code + " 错误吗信息: " + err.message, + duration: 6500, + }) + }) +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello Huks' + controller: TextInputController = new TextInputController(); + build() { + Column() { + Row() { + Text('输入您要加密得内容').fontSize(20).margin({ left: 2, top: 10 }) + } -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; -} + Row() { + TextInput({ placeholder: '默认加密123456', controller: this.controller }) + .placeholderColor(Color.Grey) + .placeholderFont({ size: 14, weight: 400 }) + .caretColor(Color.Blue) + .width(400) + .height(40) + .margin(20) + .fontSize(14) + .fontColor(Color.Black) + .type(InputType.Normal) + .onChange((value: string) => { + this.message += '您输入得明文是: ' + value + '\n' + plainText = value + }) + .margin({ top: 10 }) + } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + Row() { + Text('加密或解密的结果').fontSize(20).margin({ left: 2, top: 10 }) + } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + Row() { + TextInput({ placeholder: '这里将会显示加解密的结果', controller: this.controller }) + .placeholderColor(Color.Grey) + .placeholderFont({ size: 14, weight: 400 }) + .caretColor(Color.Blue) + .width(400) + .height(40) + .margin(20) + .fontSize(14) + .fontColor(Color.Black) + .type(InputType.Normal) + .onChange((value: string) => { + this.message += '您输入得明文是: ' + value + '\n' + plainText = value + }) + .margin({ top: 10 }) + } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); + Row() { + Button({ type: ButtonType.Normal, stateEffect: true }) { + Text('generateAesKey') + .fontColor(Color.White) + .fontSize(20) } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); + .borderRadius(8) + .width('45%') + .height('5%') + .backgroundColor(0x317aff) + .onClick(() => { + GenerateAesKey() + }) + .margin(10) + + Button({ type: ButtonType.Normal, stateEffect: true }) { + Text('deleteAesKey') + .fontColor(Color.White) + .fontSize(20) } - }); -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - let throwObject = {isThrow: false}; - try { - await updateSession(handle, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + .borderRadius(8) + .width('45%') + .height('5%') + .backgroundColor(0x317aff) + .onClick(() => { + DeleteKey() + }) + .margin(10) + } -function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); + Row() { + Button({ type: ButtonType.Normal, stateEffect: true }) { + Text('EncryptData') + .fontColor(Color.White) + .fontSize(20) } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); + .borderRadius(8) + .width('45%') + .height('5%') + .backgroundColor(0x317aff) + .onClick(() => { + EncryptData() + }) + .margin(10) + + Button({ type: ButtonType.Normal, stateEffect: true }) { + Text('DecryptData') + .fontColor(Color.White) + .fontSize(20) } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - let throwObject = {isThrow: false}; - try { - await deleteKeyItem(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -async function testSm4Cipher() { - /* 生成密钥 */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* 进行密钥加密操作 */ - await publicInitFunc(srcKeyAlias, encryptOptions); - - encryptOptions.inData = StringToUint8Array(cipherInData); - await publicUpdateFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; - - encryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } - - /* 进行解密操作 */ - await publicInitFunc(srcKeyAlias, decryptOptions); - - decryptOptions.inData = new Uint8Array(encryptUpdateResult); - await publicUpdateFunc(handle, decryptOptions); - - decryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, decryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish decrypt success '); - } else { - console.info('test finish decrypt err'); - } - - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} -``` - -### 签名验签 -```ts -/* - * 以下以SM2密钥的Callback操作使用为例 - */ -import huks from '@ohos.security.huks'; - -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let generateKeyAlias = 'sm2_Key'; -let importKeyAlias = 'importKeyAlias'; -let signVerifyInData1 = 'signVerifyInDataForTestFirstText'; -let signVerifyInData2 = 'signVerifyInDataForTestSecondText'; -let signVerifyInData = [signVerifyInData1, signVerifyInData2]; -let handle; -let exportKey; -let finishOutData; - -/* 集成生成密钥参数集 */ -let generateKeyProperties = new Array(); -generateKeyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -generateKeyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY, -} -generateKeyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -generateKeyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -let genrateKeyOptions = { - properties: generateKeyProperties, - inData: new Uint8Array(new Array()) -} - -/* 集成签名参数集 */ -let signProperties = new Array(); -signProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -signProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN -} -signProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -signProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let signOptions = { - properties: signProperties, - inData: new Uint8Array(new Array()) -} - -/* 集成验签参数集 */ -let verifyProperties = new Array(); -verifyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -verifyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY -} -verifyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -verifyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let verifyOptions = { - properties: verifyProperties, - inData: new Uint8Array(new Array()) -} - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - let throwObject = {isThrow: false}; - try { - await updateSession(handle, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback export`); - let throwObject = {isThrow: false}; - try { - await exportKeyItem(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - exportKey = data.outData; - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise importKeyItem`); - let throwObject = {isThrow: false}; - try { - await importKeyItem(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - let throwObject = {isThrow: false}; - try { - await deleteKeyItem(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -async function testSm2SignVerify() { - /* 生成密钥 */ - await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* 签名 */ - let signHandle; - let signFinishOutData; - await publicInitFunc(generateKeyAlias, signOptions); - - signHandle = handle; - for (var index = 0; index < signVerifyInData.length; index++) { - signOptions.inData = StringToUint8Array(signVerifyInData[index]); - await publicUpdateFunc(signHandle, signOptions); - } - signOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(signHandle, signOptions); - signFinishOutData = finishOutData; - - /* 导出密钥 */ - await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* 导入密钥 */ - verifyOptions.inData = exportKey; - await publicImportKeyFunc(importKeyAlias, verifyOptions); - - /* 验证签名 */ - let verifyHandle; - await publicInitFunc(importKeyAlias, verifyOptions); - - verifyHandle = handle; - for (var index = 0; index < signVerifyInData.length; index++) { - verifyOptions.inData = StringToUint8Array(signVerifyInData[index]); - await publicUpdateFunc(verifyHandle, verifyOptions); + .borderRadius(8) + .width('45%') + .height('5%') + .backgroundColor(0x317aff) + .onClick(() => { + DecryptData() + }) + .margin(10) + } } - verifyOptions.inData = signFinishOutData; - await publicFinishFunc(verifyHandle, verifyOptions); - - await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions); - await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions); + } } ``` diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 72501e07bb83ea82926ecf9a9c81c5a7bb523bd6..81de6bb49e2dd32287df60ca8a5865b8b0c36051 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -1716,4 +1716,24 @@ **授权方式**:system_grant -**ACL使能**:TRUE \ No newline at end of file +**ACL使能**:TRUE + +## ohos.permission.CONNECT_CELLULAR_CALL_SERVICE + +允许系统服务访问蜂窝通话SA。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:FALSE + +## ohos.permission.CONNECT_IMS_SERVICE + +允许系统服务访问IMS SA。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:FALSE \ No newline at end of file diff --git a/zh-cn/application-dev/security/userauth-guidelines.md b/zh-cn/application-dev/security/userauth-guidelines.md index f6b31bc96ed0635ab85a9294522de3aae7015103..80ccb1974280e59cff6f42c307a63402e6119b0f 100644 --- a/zh-cn/application-dev/security/userauth-guidelines.md +++ b/zh-cn/application-dev/security/userauth-guidelines.md @@ -17,7 +17,6 @@ userIAM_userAuth模块提供了用户认证的相关方法,包括查询认证 | 接口名称 | 功能描述 | | ---------- | ----------------------- | -| getVersion() : number | 获取认证对象的版本信息。 | | getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void | 根据指定的认证类型、认证等级,检测当前设备是否支持相应的认证能力。 | | getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance | 获取AuthInstance对象,用于执行用户身份认证。 | | on(name : AuthEventKey, callback : AuthEvent) : void | 订阅指定类型的用户认证事件。 | @@ -25,26 +24,6 @@ userIAM_userAuth模块提供了用户认证的相关方法,包括查询认证 | start: void | 执行用户认证。 | | cancel: void | 取消本次认证操作。 | -## 获取认证对象的版本信息 - -### 开发步骤 - -1. 申请权限。调用[getVersion](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetversion9)接口,需要在module.json5文件的requestPermissions对象中配置ohos.permission.ACCESS_BIOMETRIC权限。更多配置信息请参考[Stage模型应用程序包结构](../quick-start/module-configuration-file.md)。 - -2. 调用[getVersion](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetversion9)接口获取版本信息。 - - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - // 获取版本信息 - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - ``` - ## 查询当前设备是否支持相应的认证能力 ### 开发步骤 diff --git a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md index 6cd06d8b478afe22721c288591df4f3050f9ab77..f7f7437bb8285960bf9d986d82cc355456209a2f 100644 --- a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md @@ -210,7 +210,7 @@ function stopContinuousTask() { } } -class MySequenceable { +class MyParcelable { num: number = 0; str: String = ""; @@ -219,23 +219,23 @@ class MySequenceable { this.str = string; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } function sendMsgCallback(data) { console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new MySequenceable(0, "") - data.readSequenceable(receivedData) + let receivedData = new MyParcelable(0, "") + data.readParcelable(receivedData) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 if (receivedData.str === 'start_bgtask') { @@ -243,7 +243,7 @@ function sendMsgCallback(data) { } else if (receivedData.str === 'stop_bgtask') { stopContinuousTask(); } - return new MySequenceable(10, "Callee test"); + return new MyParcelable(10, "Callee test"); } export default class BgTaskAbility extends UIAbility { diff --git a/zh-cn/application-dev/ui/ui-js-components-stepper.md b/zh-cn/application-dev/ui/ui-js-components-stepper.md index bc2fbb91c69af6215bbe86cdaced35b78190e631..d91733753be4d725b8df526df0bb9bf3fb8a821b 100644 --- a/zh-cn/application-dev/ui/ui-js-components-stepper.md +++ b/zh-cn/application-dev/ui/ui-js-components-stepper.md @@ -186,7 +186,7 @@ text{ } ``` -![zh-cn_image_0000001234130975](figures/zh-cn_image_0000001234130975.PNG) +![zh-cn_image_0000001234130975](figures/zh-cn_image_0000001234130975.png) ## 添加事件 diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md index beaa8f4ac9087a663203422d16d6ee7710ca27c3..4373539cca6f91f044e37bc702aeb5fa6e6663f7 100644 --- a/zh-cn/application-dev/ui/ui-ts-animation-feature.md +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -132,7 +132,7 @@ .onAppear(() => { animateTo({ - duration: 2000, + duration: 1000, curve: this.curve1, delay: 100, onFinish: () => { @@ -199,7 +199,7 @@ .opacity(this.opacityValue) .onAppear(() => { animateTo({ - duration: 2000, + duration: 1000, curve: this.curve1, delay: 100, onFinish: () => { diff --git a/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md index 4b465482de1abb9ee8be2a5a5357714b9b806f29..e7ceeaf716393984877a77d34ee9d53c2608e62c 100644 --- a/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md +++ b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md @@ -15,12 +15,16 @@ aboutToAppear?(): void aboutToAppear函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ## aboutToDisappear aboutToDisappear?(): void aboutToDisappear函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例1:** ```ts @@ -122,6 +126,8 @@ onLayout?(children: Array\, constraint: ConstraintSizeOptions): vo 框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。 +该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 类型 | 说明 | @@ -135,6 +141,8 @@ onMeasure?(children: Array\, constraint: ConstraintSizeOptions): v 框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。 +该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 类型 | 说明 | @@ -146,6 +154,8 @@ onMeasure?(children: Array\, constraint: ConstraintSizeOptions): v 子组件布局信息。 +该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ---------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------- | | name | string | 子组件名称。 | @@ -160,6 +170,8 @@ onMeasure?(children: Array\, constraint: ConstraintSizeOptions): v 子组件border信息。 +该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ----------- | ---------------------------------------------------------- | ---------------------------------------------- | | borderWidth | [EdgeWidths](../reference/arkui-ts/ts-types.md#edgewidths) | 边框宽度类型,用于描述组件边框不同方向的宽度。 | @@ -170,6 +182,8 @@ onMeasure?(children: Array\, constraint: ConstraintSizeOptions): v 子组件layout信息。 +该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ---------- | -------------------------------------------------------------------------------- | ---------------- | | position | [Position](../reference/arkui-ts/ts-types.md#position) | 子组件位置坐标。 | 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 bf3f2929bdeb2ec2d670edab09f3eb4482aeb55f..36c046269b477392e1269e4d3750a02ac958f738 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-flex.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-flex.md @@ -38,7 +38,7 @@ .padding(10) .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.PNG) + ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) - FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection. Row相反的方向开始排布。 @@ -54,7 +54,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.PNG) + ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) - FlexDirection.Column:主轴为垂直方向,子组件从起始端沿着垂直方向开始排布。 @@ -70,7 +70,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.PNG) + ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) - FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection. Column相反的方向开始排布。 @@ -86,7 +86,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.PNG) + ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) ### 弹性布局换行 @@ -105,7 +105,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.PNG) + ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) - FlexWrap. Wrap:换行,每一行子组件按照主轴方向排列。 @@ -120,7 +120,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.PNG) + ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) - FlexWrap. WrapReverse:换行,每一行子组件按照主轴反方向排列。 @@ -135,7 +135,7 @@ .backgroundColor(0xAFEEEE) ``` - ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.PNG) + ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) ### 弹性布局对齐方式 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 6da6959c439004112f76ed51d92439306fb64edc..c2f44d025894846f7fac4cf5e6dd879b691b845a 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md @@ -106,7 +106,7 @@ listener.on('change', onPortrait) | min-device-height | 设备的最小高度。 | | max-device-height | 设备的最大高度。 | | device-width | 设备的宽度。 | -| device-type | 设备的类型。
可选值:default | +| device-type | 设备的类型。
可选值:default、tablet | | min-device-width | 设备的最小宽度。 | | max-device-width | 设备的最大宽度。 | | round-screen | 屏幕类型,圆形屏幕为true,  非圆形屏幕为  false。 | diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index d10a1bd6d103518624f07c3bfacd69599a2a2f5d..44a0cae7aee4f5bee0a29f4204b5abeca3521270 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -377,7 +377,7 @@ - 文件访问框架 - [用户公共文件访问框架概述](file-management/file-access-framework-overview.md) - [文件选择器使用指导](file-management/filepicker-guidelines.md) - - 任务管理 + - 后台任务管理 - 后台任务 - [后台任务概述](task-management/background-task-overview.md) - [短时任务开发指导](task-management/transient-task-dev-guide.md) @@ -927,6 +927,20 @@ - [@ohos.notification (Notification模块)(待停用)](reference/apis/js-apis-notification.md) - application - [EventHub](reference/apis/js-apis-inner-application-eventHub.md) + - commonEvent + - [CommonEventData](reference/apis/js-apis-inner-commonEvent-commonEventData.md) + - [CommonEventPublishData](reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md) + - [CommonEventSubscriber](reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md) + - [CommonEventSubscribeInfo](reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md) + - notification + - [NotificationActionButton](reference/apis/js-apis-inner-notification-notificationActionButton.md) + - [NotificationCommonDef](reference/apis/js-apis-inner-notification-notificationCommonDef.md) + - [NotificationContent](reference/apis/js-apis-inner-notification-notificationContent.md) + - [NotificationFlags](reference/apis/js-apis-inner-notification-notificationFlags.md) + - [NotificationRequest](reference/apis/js-apis-inner-notification-notificationRequest.md) + - [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md) + - [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.md) + - [NotificationUserInput](reference/apis/js-apis-inner-notification-notificationUserInput.md) - 包管理 - [@ohos.bundle.appControl (appControl模块)](reference/apis/js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager模块)](reference/apis/js-apis-bundleManager.md) @@ -981,7 +995,7 @@ - [@ohos.i18n (国际化-I18n)](reference/apis/js-apis-i18n.md) - [@ohos.intl (国际化-Intl)](reference/apis/js-apis-intl.md) - [@ohos.resourceManager (资源管理)](reference/apis/js-apis-resource-manager.md) - - 资源调度 + - 后台任务 - [@ohos.distributedMissionManager (分布式任务管理)](reference/apis/js-apis-distributedMissionManager.md) - [@ohos.reminderAgentManager (后台代理提醒)](reference/apis/js-apis-reminderAgentManager.md) - [@ohos.resourceschedule.backgroundTaskManager (后台任务管理)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) @@ -1229,8 +1243,9 @@ - 资源管理 - [I18n错误码](reference/errorcodes/errorcode-i18n.md) - [资源管理错误码](reference/errorcodes/errorcode-resource-manager.md) - - 资源调度 + - 后台任务 - [backgroundTaskManager错误码](reference/errorcodes/errorcode-backgroundTaskMgr.md) + - [DeviceUsageStatistics错误码](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - [reminderAgentManager错误码](reference/errorcodes/errorcode-reminderAgentManager.md) - [workScheduler错误码](reference/errorcodes/errorcode-workScheduler.md) - 安全 @@ -1280,7 +1295,6 @@ - [系统参数错误码](reference/errorcodes/errorcode-system-parameterV9.md) - [USB服务错误码](reference/errorcodes/errorcode-usb.md) - [升级错误码](reference/errorcodes/errorcode-update.md) - - [DeviceUsageStatistics错误码](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - 定制管理 - [企业设备管理错误码](reference/errorcodes/errorcode-enterpriseDeviceManager.md) - 语言基础类库 diff --git "a/zh-cn/contribute/\345\206\231\344\275\234\350\247\204\350\214\203.md" "b/zh-cn/contribute/\345\206\231\344\275\234\350\247\204\350\214\203.md" index 556baff875baa8ee7927e5fc035885d4c4a61dfa..d8ee9fef5ee8aaca3c189d141ec85a59c096da6f 100755 --- "a/zh-cn/contribute/\345\206\231\344\275\234\350\247\204\350\214\203.md" +++ "b/zh-cn/contribute/\345\206\231\344\275\234\350\247\204\350\214\203.md" @@ -67,7 +67,7 @@ - 中文用中文图,英文用英文图形。 - 图片建议根据内容命名,只用数字序列不利于后续图片的继承。 ->![](public_sys-resources/icon-note.gif) **说明**: +>**说明**: >引用方式: >!\[\]\(./pic/pic-standard.png\) diff --git "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" index 8092b528d1960f5a83df17416cded1c565b37c32..1d7524fc65ec1d3aa782a5c5eb49803effd680e7 100755 --- "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" +++ "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" @@ -36,7 +36,7 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , 8. 不能引入有高危漏洞且无解决方案的版本。 9. 若需针对引入的开源软件进行修改,请将修改的代码放在该开源软件仓中,并确保满足该开源软件的许可证要求,修改的文件应当保持其原始许可证条款,新增的文件也建议采用相同的许可证条款。 10. 新引入的开源软件必须在其根目录提供README.OpenSource文件,在该文件中准确描述其软件名、许可证、许可文件位置、版本、对应版本的上游社区地址、软件的维护Owner、功能描述以及引入的原因。 -11. 引入新软件到OpenHarmony时必须有对应的SIG负责管理,原则上如果没有SIG-Compliance以及相应SIG的确认,SIG-Architecture不批准相应软件的引入。当要批量引入多个软件时,可以求助SIG-Architecture主持发起SIG间的临时评审会议,提升协调效率。如因特殊原因不能满足上述要求但又需要引入,请请联系邮箱:oh-legal@openatom.io。 +11. 引入新软件到OpenHarmony时必须有对应的SIG负责管理,原则上如果没有SIG-Compliance以及相应SIG的确认,SIG-Architecture不批准相应软件的引入。当要批量引入多个软件时,可以求助SIG-Architecture主持发起SIG间的临时评审会议,提升协调效率。如因特殊原因不能满足上述要求但又需要引入,请联系邮箱:oh-legal@openatom.io。 12. 引入新的开源软件存在依赖其他开源软件时,不允许将被动依赖软件嵌套在引入的新的开源软件子目录中,必须剥离所有依赖软件项,并将其分别放置到单独的代码仓,命名统一为third_party_依赖软件名称,原因是嵌套放置依赖软件可能导致多同一款软件多版本、旧版本安全漏洞无法及时修复、开源义务履行合规的风险问题。 - 依赖软件在编译构建部件命名,将新引入的主软件名作为依赖软件部件前缀命名,例如 part_name = "新引入主软件名_依赖软件名" - 新引入软件和依赖软件分别独立构建,通过external_deps来解决部件间依赖。 diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" "b/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" index a5a9bd99d8f20247f68efa03b5e067ee65f2f76c..397ec70f4bef209c5bfe8dda393c160f5d440a2e 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" @@ -26,7 +26,7 @@ 1. 在Gitee页面中,“Issue”页签中单击“新建Issue”,在标题栏中描述问题,在编辑框中添加详细问题描述。 2. 单击“创建”按钮,提交Issue,耐心等待文档团队成员确认您的问题。 ->![](public_sys-resources/icon-note.gif) **说明**: +>**说明**: >**如何反馈一个高质量的问题**? > >- 提供问题的清晰描述,描述具体缺失、过时、错误的内容或者需要改进的文字。 diff --git a/zh-cn/device-dev/Readme-CN.md b/zh-cn/device-dev/Readme-CN.md index 75f58ab4228925d2c57096ed3d2d29cff2e28314..d85370b5314c3d80254582f529f124f240307404 100644 --- a/zh-cn/device-dev/Readme-CN.md +++ b/zh-cn/device-dev/Readme-CN.md @@ -41,7 +41,6 @@ - [AI框架](subsystems/subsys-ai-aiframework-devguide.md) - [数据管理](subsystems/subsys-data-relational-database-overview.md) - [Sensor服务](subsystems/subsys-sensor-overview.md) - - [USB服务](subsystems/subsys-usbservice-overview.md) - [用户程序框架](subsystems/subsys-application-framework-overview.md) - [OTA升级](subsystems/subsys-ota-guide.md) - [电话服务](subsystems/subsys-tel-overview.md) diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 15c23f13f1d0ab86dbf5a241ed87471a456f5b10..a547550a2e517f8b9daa1868abc72cdb63a0e12b 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -50,10 +50,6 @@ - [Sensor服务概述](subsys-sensor-overview.md) - [Sensor服务使用指导](subsys-sensor-guide.md) - [Sensor服务使用实例](subsys-sensor-demo.md) -- USB服务 - - [USB服务概述](subsys-usbservice-overview.md) - - [USB服务使用指导](subsys-usbservice-guide.md) - - [USB服务使用实例](subsys-usbservice-demo.md) - 用户程序框架 - [概述](subsys-application-framework-overview.md) - [搭建环境](subsys-application-framework-envbuild.md) @@ -109,3 +105,6 @@ - [bytrace使用指导](subsys-toolchain-bytrace-guide.md) - [hdc使用指导](subsys-toolchain-hdc-guide.md) - [hiperf使用指导](subsys-toolchain-hiperf.md) +- 电源管理 + - 显示管理 + - [系统亮度范围定制开发指导](subsys-power-brightness-customization.md) diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812333.png b/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812333.png deleted file mode 100644 index 76fd15e43b8ccf8566ed55cc0592d3f3e6580319..0000000000000000000000000000000000000000 Binary files a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812333.png and /dev/null differ diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812334.png b/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812334.png new file mode 100644 index 0000000000000000000000000000000000000000..0a91177b3004ff030d3ff86b79e2193f52725f87 Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001261812334.png differ diff --git a/zh-cn/device-dev/subsystems/subsys-build-all.md b/zh-cn/device-dev/subsystems/subsys-build-all.md index 442f7ba0091615cad7e19198a088c192721418c4..b6bddb7fb95fef31be91e2c937ec6692e78eb1bc 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-all.md +++ b/zh-cn/device-dev/subsystems/subsys-build-all.md @@ -353,4 +353,4 @@ optional arguments: - [开源软件Notice收集策略说明](subsys-build-reference.md#开源软件notice收集策略说明) - [加快本地编译的一些参数](subsys-build-reference.md#加快本地编译的一些参数) - [查看NinjaTrace](subsys-build-reference.md#查看ninjatrace) - +- [定制打包chip_prod镜像使用说明](subsys-build-reference.md#定制打包chip_prod镜像使用说明) diff --git a/zh-cn/device-dev/subsystems/subsys-build-reference.md b/zh-cn/device-dev/subsystems/subsys-build-reference.md index bd1fee97a1b26f4cbd837ce200ef00302bd87a66..528439c06450441ab481ebb66e85b6ef4e0685f0 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-reference.md +++ b/zh-cn/device-dev/subsystems/subsys-build-reference.md @@ -192,3 +192,61 @@ out/rk3568/.ninja_log文件记录了每个模块编译的开始和结束时间(m 1. 点击静态检查下的“成功”; 2. 点击输出列的“输出”即可在左侧的build_trace列看到build.trace.html文件,单击该文件即可打开。 + +## 定制打包chip_prod镜像使用说明 + +### 背景 + +针对同一个芯片解决方案下的子产品的定制能力,将差异能力放到 chip_prod 分区,因此需要支持对不同子产品生成对应的 chip_prod.img。 + +### 使用步骤 +1. 产品解决方案配置:
+ 产品解决方案配置文件config.json中添加`"chipprod_config_path"`配置选项,即`"chipprod_config_path":"子产品定义文件所在的路径"`。 + 其中子产品定义文件的文件名为`chip_product_list.gni`,文件格式为:`chip_product_list = ["productA", "productB", ...]` 。
+ 示例:
+ 以MyProduct产品定制chipprod镜像为例,//vendor/产品厂商/MyProduct/config.json配置如下: + ```shell + { + "product_name": "MyProduct", # 产品名称 + "version": "3.0", # config.json的版本号, 固定"3.0" + "chipprod_config_path": "", # 存放chipprod配置文件路径,可选项 + "subsystems": [ + { + "subsystem": "arkui", # 选择的子系统 + "components": [ + { + "component": "ace_engine", + "features":[ "ace_engine_feature_enable_web = true", + "ace_engine_feature_enable_accessibility = true" ] } + ] + }, + { + ...... + } + ...... + 更多子系统和部件 + } + } + ``` + +2. 模块编译配置:
+ 某个配置文件在不同的子产品中有差异,比如要打包到productA对应的chip_prod.img中,则模块编译需要配置`install_images`和`module_install_dir`。
+ 以`ohos_prebuilt_executable`示例: + ```shell + ohos_prebuilt_executable("moduleXXX"){ + install_images = [ "chip_prod" ] + module_install_dir = "productA/etc/***" # module_install_dir指定的路径需要以productA开始。 + } + ``` + +3.编译命令 +```shell +./build.sh --product-name {product_name} --build-target chip_prod_image +``` + +4. 打包结果:
+ 如果定义了子产品productA和productB,即`chip_product_list = ["productA", "productB"],`并且有模块安装到了该产品下,则打包后镜像输出路径如下: + ``` + images/productA/chip_prod.img + images/productB/chip_prod.img + ``` \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-faultlogger.md b/zh-cn/device-dev/subsystems/subsys-dfx-faultlogger.md index b290303ffdac4b6f3fb877e0436e793f7f365f4a..06e91d7b7f0a19ee6418efcce03cfd9222bc3a15 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-faultlogger.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-faultlogger.md @@ -18,15 +18,15 @@ FaultLogger承载OpenHarmony系统上的故障记录功能,按照服务对象 **图1** 进程崩溃处理流程图 -![zh-cn_image_0000001261812333](figures/zh-cn_image_0000001261812333.png) +![zh-cn_image_0000001261812333](figures/zh-cn_image_0000001261812334.png) -1. 进程安装信号处理器后,通过DFX_SignalHandler函数检测并响应进程崩溃异常信号; +1. 进程安装信号处理器后,通过DFX_SignalHandler函数检测并响应由Kernel抛出的进程崩溃异常信号; 2. SignalHandler检测到异常信号后Fork出子进程,并运行ProcessDump程序开始dump崩溃进程和线程的堆栈信息; -3. ProcessDump程序在读取异常堆栈信息后将日志写入到Faultloggerd中的临时存储目录,进而生成完整的崩溃日志; +3. ProcessDump程序向Faultloggerd服务申请用于存储故障日志的文件句柄,在读取到异常堆栈信息后写入到该文件中,进而生成完整的崩溃日志; -4. Faultloggerd根据需要将故障通过Hiview提供的AddFaultLog()接口进行上报,hiview将处理生成简化的崩溃日志,并上报Hisysevent事件。 +4. ProcessDump完成崩溃日志收集后,根据需要将故障通过Hiview提供的AddFaultLog()接口进行上报,hiview将处理生成简化的崩溃日志,并上报Hisysevent事件。 基于这样的设计,在资源有限的小型系统上可只部署Faultloggerd,也依然可以获取用于定位崩溃问题的日志。 @@ -39,14 +39,14 @@ Faultloggerd意在为开发者在开发测试过程中遇到的崩溃或卡死 **表1** Faultloggerd模块应用场景 -| 场景描述 | 使用工具 | 使用方式 | +| 场景描述 | 使用工具 | 使用方式 | | -------- | -------- | -------- | -| 了解函数的调用顺序 | DumpCatcher API | 参见:[使用DumpCatcher获取调用栈](#使用dumpcatcher获取调用栈) | -| 应用卡死/CPU占用高 | ProcessDump | 参见:[使用ProcessDump获取调用栈](#使用processdump获取调用栈) | -| 进程未处理信号崩溃 | 崩溃日志和addr2line工具 | 参见:[基于崩溃日志对问题进行定位](#基于崩溃日志对问题进行定位) | +| 了解函数的调用顺序 | DumpCatcher API | 参见:[使用DumpCatcher接口获取调用栈](#使用dumpcatcher接口获取调用栈) | +| 应用卡死/CPU占用高 | DumpCatcher Command Tool | 参见:[使用DumpCatcher命令获取调用栈](#使用dumpcatcher命令获取调用栈) | +| 崩溃问题定位 | 崩溃日志和addr2line工具 | 参见:[基于崩溃日志定位问题](#基于崩溃日志定位问题) | -## 使用DumpCatcher获取调用栈 +## 使用DumpCatcher接口获取调用栈 ### 接口说明 @@ -55,57 +55,70 @@ DumpCatcher可以抓取OpenHarmony指定进程(线程)的调用栈。 **表2** DumpCatcher接口说明 -| 类 | 方法 | 描述 | +| 类 | 方法 | 描述 | | -------- | -------- | -------- | -| DfxDumpCatcher | bool DumpCatch(const int pid, const int tid, std::string& msg) |   接口返回值:
- true:回栈成功,回栈信息存储在msg字符串对象中;
- false:回栈失败。
  输入参数:
- pid:目标进程号;
- tid:目标线程号,如果需要回栈进程中的所有线程,则tid设定为0;
  输出参数:
- msg:如果回栈成功,则通过msg返回调用栈信息。 | +| DfxDumpCatcher | bool DumpCatch(const int pid, const int tid, std::string& msg) | 接口返回值:
- true:回栈成功,回栈信息存储在msg字符串对象中;
- false:回栈失败。
输入参数:
- pid:目标进程号;
- tid:目标线程号,如果需要回栈进程中的所有线程,则tid设定为0;
输出参数:
- msg:如果回栈成功,则通过msg返回调用栈信息。 | +| DfxDumpCatcher | bool DumpCatchMix(const int pid, const int tid, std::string& msg) | 接口返回值:
- true:回栈成功,回栈信息存储在msg字符串对象中;
- false:回栈失败。
输入参数:
- pid:目标进程号;
- tid:目标线程号,如果需要回栈进程中的所有线程,则tid设定为0;
输出参数:
- msg:如果回栈成功,则通过msg返回混合栈信息。 | +| DfxDumpCatcher | bool DumpCatchFd(const int pid, const int tid, std::string& msg, int fd) | 接口返回值:
- true:回栈成功,回栈信息存储在msg字符串对象中;
- false:回栈失败。
输入参数:
- pid:目标进程号;
- tid:目标线程号,如果需要回栈进程中的所有线程,则tid设定为0;
- fd:指定写入的文件句柄号;
输出参数:
- msg:如果回栈成功,则通过msg返回调用栈信息。 | +| DfxDumpCatcher | bool DumpCatchMultiPid(const std::vector\ pidV, std::string& msg) | 接口返回值:
- true:回栈成功,回栈信息存储在msg字符串对象中;
- false:回栈失败。
输入参数:
- pidV:目标进程号列表;
输出参数:
- msg:如果回栈成功,则通过msg返回调用栈信息。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 当调用此接口的进程id与目标pid不一致时需要调用者是管理员(system,root)用户。当抓取非本用户组进程调用栈时还需具备读取对方/proc/pid/maps及ptrace到对方进程的权限。 +> 当调用此接口的进程id与目标pid不一致时需要调用者是管理员(system,root)用户。 ### 开发实例 -系统应用开发者可以用DumpCatcher在自己的应用中获取指定进程(线程)的调用栈。下文以dumpcatcherdemo模块使用DumpCatcher接口获取调用栈作为实例进行讲解。 +系统应用开发者可以用DumpCatcher在自己的应用中获取指定进程(线程)的调用栈。下文以dumpcatcherdemo模块使用DumpCatcher基础接口获取调用栈作为实例进行讲解。 1. 编译构建文件添加dumpcatcher依赖:以/base/hiviewdfx/faultloggerd/example/BUILD.gn为例,在include_dirs中添加DfxDumpCatcher头文件路径,并在deps中添加“//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher”模块依赖。 - + ``` import("//base/hiviewdfx/faultloggerd/faultloggerd.gni") import("//build/ohos.gni") - + config("dumpcatcherdemo_config") { visibility = [ ":*" ] - + include_dirs = [ ".", "//utils/native/base/include", "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher/include/", # 添加dumpcatcher头文件路径 ] } - - ohos_executable("dumpcatcherdemo") { sources = [ "dump_catcher_demo.cpp" ] configs = [ ":dumpcatcherdemo_config" ] deps = [ "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher", # 添加dumpcathcer模块依赖 "//utils/native/base:utils", ] external_deps = [ "hilog_native:libhilog" ] install_enable = true part_name = "faultloggerd" subsystem_name = "hiviewdfx" + + ohos_executable("dumpcatcherdemo") { + sources = [ "dump_catcher_demo.cpp" ] + configs = [ ":dumpcatcherdemo_config" ] + deps = [ + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher", # 添加dumpcathcer模块依赖 + "//utils/native/base:utils", + ] + external_deps = [ "hilog_native:libhilog" ] + install_enable = true + part_name = "faultloggerd" + subsystem_name = "hiviewdfx" } ``` 2. 头文件定义用到的函数:以/base/hiviewdfx/faultloggerd/example/dump_catcher_demo.h为例,本样例代码中,通过调用栈深度测试的测试函数来构造一个指定深度的调用栈。 - + ``` #ifndef DUMP_CATCHER_DEMO_H #define DUMP_CATCHER_DEMO_H - + #include - + #define NOINLINE __attribute__((noinline)) - + // 定义该宏函数用于自动生成函数调用链 #define GEN_TEST_FUNCTION(FuncNumA, FuncNumB) \ __attribute__((noinline)) int TestFunc##FuncNumA() \ { \ return TestFunc##FuncNumB(); \ } - + // 调用栈深度测试的测试函数 int TestFunc0(void); int TestFunc1(void); @@ -118,22 +131,22 @@ DumpCatcher可以抓取OpenHarmony指定进程(线程)的调用栈。 int TestFunc8(void); int TestFunc9(void); int TestFunc10(void); - + #endif // DUMP_CATCHER_DEMO_H ``` 3. 在源文件中调用DumpCatch接口:以/base/hiviewdfx/faultloggerd/example/dump_catcher_demo.cpp为例,引用dfx_dump_catcher.h头文件,声明DfxDumpCatcher对象,通过宏函数构造函数调用链,并最后调用DumpCatch接口方法,传入需要抓取调用栈的进程号、线程号。 - + ``` #include "dump_catcher_demo.h" - + #include #include #include // dfx_dump_catcher.h头文件引入 #include "dfx_dump_catcher.h" using namespace std; - + NOINLINE int TestFunc10(void) { OHOS::HiviewDFX::DfxDumpCatcher dumplog; @@ -144,7 +157,7 @@ DumpCatcher可以抓取OpenHarmony指定进程(线程)的调用栈。 } return 0; } - + // 通过宏函数自动生成函数调用链 GEN_TEST_FUNCTION(0, 1) GEN_TEST_FUNCTION(1, 2) @@ -156,7 +169,7 @@ DumpCatcher可以抓取OpenHarmony指定进程(线程)的调用栈。 GEN_TEST_FUNCTION(7, 8) GEN_TEST_FUNCTION(8, 9) GEN_TEST_FUNCTION(9, 10) - + int main(int argc, char *argv[]) { TestFunc0(); @@ -165,55 +178,57 @@ DumpCatcher可以抓取OpenHarmony指定进程(线程)的调用栈。 ``` -## 使用ProcessDump获取调用栈 +## 使用DumpCatcher命令获取调用栈 ### 工具说明 -ProcessDump是一个抓取调用栈的命令行工具,在OpenHarmony系统中可直接使用,该工具通过-p、-t参数指定进程和线程,命令执行后在命令行窗口打印指定进程的线程栈信息。 +DumpCatcher Command Tool是一个抓取调用栈的命令行工具,在OpenHarmony系统中可直接使用,该工具通过-p、-t参数指定进程和线程,命令执行后在命令行窗口打印指定进程的线程栈信息。还可通过添加-m参数来抓取应用进程的JS Native混合栈。 - **表3** ProcessDump命令行工具使用说明 + **表3** DumpCatcher Command Tool使用说明 -| 工具名称 | 命令行工具路径 | 执行命令 | 描述 | +| 工具名称 | 命令行工具路径 | 执行命令 | 描述 | | -------- | -------- | -------- | -------- | -| processdump | /system/bin | - processdump -p [pid]
- processdump -p [pid] -t [tid] | **参数说明:**
- -p [pid]:打印指定进程下面的所有线程栈信息。
- -p [pid] -t [tid]:打印指定进程下面的指定线程信息。
**返回值说明:**
如果栈信息解析成功,则将信息显示到标准输出;失败则打印错误信息。 | - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 此工具需要在root下使用,或调用者有权限ptrace到目标进程,并读取目标进程的smaps。 +| dumpcatcher | /system/bin | - dumpcatcher -p [pid]
- dumpcatcher -p [pid] -t [tid]
- dumpcatcher -m -p [pid]
- dumpcatcher -m -p [pid] -t [tid]
| **参数说明:**
- -p [pid]:打印指定进程下面的所有线程栈信息。
- -p [pid] -t [tid]:打印指定进程下面的指定线程信息。
- -m -p [pid]:打印指定进程下面的所有线程混合栈信息。
- -m -p [pid] -t [tid]:打印指定进程下面的指定线程混合栈信息。
**返回值说明:**
如果栈信息解析成功,则将信息显示到标准输出;失败则打印错误信息。 | ### 使用实例 -通过processdump命令行工具打印hiview进程的调用栈。 +通过dumpcatcher命令打印hiview进程的调用栈。 + - ``` -# ps -A | grep hiview - 114 ? 00:00:00 hiview -# processdump -p 114 -t 114 -Tid:114, Name:hiview -#00 pc 0000000000089824(00000000b6f44824) /system/lib/ld-musl-arm.so.1(ioctl+68) -#01 pc 000000000002a709(00000000b6c56709) /system/lib/libipc_core.z.so(_ZN4OHOS15BinderConnector11WriteBinderEmPv+16) -#02 pc 000000000002ba75(00000000b6c57a75) /system/lib/libipc_core.z.so(_ZN4OHOS13BinderInvoker18TransactWithDriverEb+224) -#03 pc 000000000002bb37(00000000b6c57b37) /system/lib/libipc_core.z.so(_ZN4OHOS13BinderInvoker13StartWorkLoopEv+22) -#04 pc 000000000002c211(00000000b6c58211) /system/lib/libipc_core.z.so(_ZN4OHOS13BinderInvoker10JoinThreadEb+36) -#05 pc 0000000000038d07(00000000004bcd07) /system/bin/hiview(_ZNSt3__h6vectorINS_9sub_matchINS_11__wrap_iterIPKcEEEENS_9allocatorIS6_EEE8__appendEj+596) -#06 pc 0000000000028655(00000000004ac655) /system/bin/hiview -#07 pc 00000000000c2b08(00000000b6f7db08) /system/lib/ld-musl-arm.so.1(__libc_start_main+116) -#08 pc 00000000000285f4(00000000004ac5f4) /system/bin/hiview -#09 pc 0000000000028580(00000000004ac580) /system/bin/hiview +# ps -ef |grep hiview +hiview 240 1 0 17:01:49 ? 00:00:14 hiview +root 1822 1560 7 20:56:36 pts/0 00:00:00 grep hiview +# dumpcatcher -p 240 -t 240 +Result: 0 ( no error ) +Timestamp:2017-08-05 20:56:43.000 +Pid:240 +Uid:1201 +Process name:/system/bin/hiview +Tid:240, Name:hiview +#00 pc 00098f8c /system/lib/ld-musl-arm.so.1(ioctl+68) +#01 pc 0000e2a1 /system/lib/chipset-pub-sdk/libipc_single.z.so +#02 pc 0000ed59 /system/lib/chipset-pub-sdk/libipc_single.z.so +#03 pc 0000ee1f /system/lib/chipset-pub-sdk/libipc_single.z.so +#04 pc 0000f745 /system/lib/chipset-pub-sdk/libipc_single.z.so +#05 pc 00037577 /system/bin/hiview +#06 pc 00025973 /system/bin/hiview +#07 pc 000db210 /system/lib/ld-musl-arm.so.1 +#08 pc 000258d8 /system/bin/hiview +#09 pc 0002587c /system/bin/hiview ``` -## 基于崩溃日志对问题进行定位 +## 基于崩溃日志定位问题 开发者可以通过faultloggerd生成的崩溃堆栈日志进行问题定位。本章节将主要介绍如何利用addr2line工具进行崩溃问题定位。 1. 程序自崩溃或构造崩溃。 例如将如下代码植入自己的代码中,调用触发一个无效内存访问故障(SIGSEGV)。 - + ``` NOINLINE int TriggerSegmentFaultException() { @@ -226,42 +241,43 @@ Tid:114, Name:hiview ``` 2. 获取崩溃函数调用栈日志。 - 因为存在未处理的异常,进程会在 /data/log/faultlog/temp路径下生成临时的日志文件,其命名规则为: + 因为存在未处理的异常,进程会在/data/log/faultlog/temp路径下生成临时的日志文件,其命名规则为: + - ``` cppcrash-pid-time ``` 获取其生成的调用栈如下: - + ``` + Timestamp:2017-08-05 17:35:03.000 Pid:816 Uid:0 - Process name:./crasher + Process name:./crasher_c Reason:Signal:SIGSEGV(SEGV_ACCERR)@0x0042d33d Fault thread Info: Tid:816, Name:crasher + #00 pc 0000332c /data/crasher(TriggerSegmentFaultException+15)(8bc37ceb8d6169e919d178fdc7f5449e) + #01 pc 000035c7 /data/crasher(ParseAndDoCrash+277)(8bc37ceb8d6169e919d178fdc7f5449e) + #02 pc 00003689 /data/crasher(main+39)(8bc37ceb8d6169e919d178fdc7f5449e) + #03 pc 000c3b08 /system/lib/ld-musl-arm.so.1(__libc_start_main+116) + #04 pc 000032f8 /data/crasher(_start_c+112)(8bc37ceb8d6169e919d178fdc7f5449e) + #05 pc 00003284 /data/crasher(_start+32)(8bc37ceb8d6169e919d178fdc7f5449e) + Registers: r0:0042d33d r1:0000000b r2:1725d4c4 r3:b6f9fa84 r4:bec97e69 r5:b6fc0268 r6:0042d661 r7:bec97d60 r8:00000000 r9:00000000 r10:00000000 fp:bec97d20 ip:00000020 sp:bec97cd0 lr:b6f9fae4 pc:0042d32c - - #00 pc 000000000000332c(000000000042d32c) /data/crasher(TriggerSegmentFaultException+15) - #01 pc 00000000000035c7(000000000042d5c7) /data/crasher(ParseAndDoCrash+277) - #02 pc 0000000000003689(000000000042d689) /data/crasher(main+39) - #03 pc 00000000000c3b08(00000000b6fbbb08) /system/lib/ld-musl-arm.so.1(__libc_start_main+116) - #04 pc 00000000000032f8(000000000042d2f8) /data/crasher(_start_c+112) - #05 pc 0000000000003284(000000000042d284) /data/crasher(_start+32) ``` 3. 利用addr2line工具进行调用栈分析。 使用addr2line工具根据偏移地址解析行号: - + ``` - root:~/OpenHarmony/out/hi3516dv300/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 000332c + root:~/OpenHarmony/out/hi3516dv300/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c base/hiviewdfx/faultloggerd/tools/crasher/dfx_crasher.c:57 ``` diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md index 285a917f36d6e4491b333cb619c81e572acb3497..175b49816ea59a74ed28651cdca2b607fc8f1c7d 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @@ -6,18 +6,18 @@ ### 功能简介 -组件若有HiSysEvent事件的打点需求,则需要先定义yaml文件并在bundle.json文件中[配置yaml文件的路径](subsys-dfx-hisysevent-logging-config.md#配置yaml文件路径)。OpenHarmony编译框架在编译过程中则会通过python编译脚本解析校验bundle.json文件指定的所有yaml文件。在解析校验之后,编译框架会将这些yaml文件中配置的信息汇总转换成名为hisysevent.def的json文件。最后,将此json文件打包到系统指定路径下,用作HiSysEvent事件落盘的判断依据。 +组件若有HiSysEvent事件的打点需求,则需要先定义yaml文件并在bundle.json文件中[配置yaml文件的路径](subsys-dfx-hisysevent-logging-config.md#验证yaml文件)。OpenHarmony编译框架在编译过程中则会通过python编译脚本解析校验bundle.json文件指定的所有yaml文件。在解析校验之后,编译框架会将这些yaml文件中配置的信息汇总转换成名为hisysevent.def的json文件。最后,将此json文件打包到系统指定路径下,用作HiSysEvent事件落盘的判断依据。 ### 基本概念 在配置HiSysEvent打点之前,开发者应了解以下基本概念: -- 事件领域 用于标识事件所属的领域,在yaml文件中以domain为键值指定,可参考yaml文件样例中的[domain](subsys-dfx-hisysevent-logging-config.md#编写样例)。 +- 事件领域 用于标识事件所属的领域,在yaml文件中以domain为键值指定,可参考yaml文件样例中的[domain](subsys-dfx-hisysevent-logging-config.md#编写yaml文件)。 -- 事件名称 用于指定事件领域包含的所有事件,可参考yaml文件样例中的[EVENT_NAMEA/EVENT_NAMEB](subsys-dfx-hisysevent-logging-config.md#编写样例)。 +- 事件名称 用于指定事件领域包含的所有事件,可参考yaml文件样例中的[EVENT_NAMEA/EVENT_NAMEB](subsys-dfx-hisysevent-logging-config.md#编写yaml文件)。 -- 参数 用于定义某个事件名称包含的所有键值,可参考yaml文件样例中的[__BASE/NAME1/NAME2](subsys-dfx-hisysevent-logging-config.md#编写样例)。 +- 参数 用于定义某个事件名称包含的所有键值,可参考yaml文件样例中的[__BASE/NAME1/NAME2](subsys-dfx-hisysevent-logging-config.md#编写yaml文件)。 ### 约束与限制 @@ -47,10 +47,13 @@ | desc | 字段作用:必选字段,用来对该参数进行描述。
定义规则:
- 至少包含3个字符,最多包含128个字符,字符范围[a-zA-Z0-9 _] | -## 编写yaml文件 +## 开发步骤 -### 编写规则 +### 编写yaml文件 + + +**编写规则** - 事件领域命名规则: - 字母开头,且只能由大写字母/数字/下划线组成; @@ -63,11 +66,11 @@ - 参数命名规则: - 字母开头,且只能由大写字母/数字/下划线组成; - - 字符串长度取值范围1~32; + - 字符串长度取值范围1~48; - 单个事件名称内包含的参数的个数不能超过128个。 -### 编写样例 +**编写样例** - yaml文件样例指定的事件领域名称为MODULEA,该事件领域包含两个事件,名称分别是EVENT_NAMEA和EVENT_NAMEB。 @@ -95,10 +98,10 @@ ``` -## 验证yaml文件 +### 验证yaml文件 -### 配置yaml文件路径 +**配置yaml文件路径** 在bundle.json文件中通过hisysevent_config属性完成yaml文件的路径指定: @@ -149,7 +152,7 @@ > yaml文件可根据实际需求置于组件工程的任意目录下,只要在bundle.json文件指定即可。 -### 编译yaml文件 +**编译yaml文件** - 全量编译: - 全量编译整个系统,会将所有组件配置的yaml文件中的配置进行汇总,正常完成系统编译后,指定目录下就会生成hisysevent.def文件。 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-overview.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-overview.md index 65f825ea1bacf5f9c8bdf59897e74a2023ba4852..ce9d2adb2545c64a6ce3437208bf57601f3e10bb 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-overview.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-overview.md @@ -1,7 +1,7 @@ # HiSysEvent概述 -## 概述 +## 简介 HiSysEvent是面向OpenHarmony系统开发者提供的系统打点功能,通过在关键路径埋点来记录系统在运行过程中的重要信息,辅助开发者定位问题,此外还支持开发者将打点数据上传到云进行大数据质量度量。 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hitracechain.md b/zh-cn/device-dev/subsystems/subsys-dfx-hitracechain.md index 1c2cdf491de1474253287ada866d2de343d83553..0659079bcca77980e3655d16a0834f2b3e074678 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hitracechain.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hitracechain.md @@ -51,58 +51,90 @@ HiTraceChain实现在C层,主要原理是在一次业务调用流程中,利 | | **C++** | **C** | | -------- | -------- | -------- | | **类** | **函数** | **函数** | -| HiTraceChain | HiTraceId Begin(const std::string& name, int flags) | HiTraceIdStruct HiTraceChainBegin(const char\* name, int flags) | -| | void End(const HiTraceId& id) | void HiTraceChainEnd(const HiTraceIdStruct\* pId) | -| | HiTraceId GetId(); | HiTraceIdStruct HiTraceChainGetId() | -| | void SetId(const HiTraceId& id) | void HiTraceChainSetId(const HiTraceIdStruct\* pId) | -| | void ClearId() | void HiTraceChainClearId() | -| | HiTraceId CreateSpan() | HiTraceIdStruct HiTraceChainCreateSpan() | -| | void Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char\* fmt, ...) | void HiTraceChainTracepoint(HiTraceTracepointType type, const HiTraceIdStruct_ pId, const char_ fmt, ...) | -| | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id, const char\* fmt, ...) | void HiTraceChainTracepointEx(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceIdStruct_ pId, const char_ fmt, ...) | -| HiTraceId | HiTraceId(); | void HiTraceChainInitId(HiTraceIdStruct\* pId) | -| | HiTraceId(const uint8_t\* pIdArray, int len) | HiTraceIdStruct HiTraceChainBytesToId(const uint8_t\* pIdArray, int len) | -| | bool IsValid() | int HiTraceChainIsValid(const HiTraceIdStruct\* pId) | -| | bool IsFlagEnabled(HiTraceFlag flag) | int HiTraceChainIsFlagEnabled(const HiTraceIdStruct\* pId, HiTraceFlag flag) | -| | void EnableFlag(HiTraceFlag flag) | void HiTraceChainEnableFlag(HiTraceIdStruct\* pId, HiTraceFlag flag) | -| | int GetFlags() | int HiTraceChainGetFlags(const HiTraceIdStruct\* pId) | -| | void SetFlags(int flags) | void HiTraceChainSetFlags(HiTraceIdStruct\* pId, int flags) | -| | uint64_t GetChainId() | uint64_t HiTraceChainGetChainId(const HiTraceIdStruct\* pId) | -| | void SetChainId(uint64_t chainId) | void HiTraceChainSetChainId(HiTraceIdStruct\* pId, uint64_t chainId) | -| | uint64_t GetSpanId() | uint64_t HiTraceChainGetSpanId(const HiTraceIdStruct\* pId) | -| | void SetSpanId(uint64_t spanId) | void HiTraceChainSetSpanId(HiTraceIdStruct\* pId, uint64_t spanId) | -| | uint64_t GetParentSpanId() | uint64_t HiTraceChainGetParentSpanId(const HiTraceIdStruct\* pId) | -| | void SetParentSpanId(uint64_t parentSpanId) | void HiTraceChainSetParentSpanId(HiTraceIdStruct\* pId, uint64_t parentSpanId) | -| | int ToBytes(uint8_t\* pIdArray, int len) | int HiTraceChainIdToBytes(const HiTraceIdStruct_ pId, uint8_t_ pIdArray, int len) | +| HiTraceChain | HiTraceId Begin(const std::string& name, int flags) | HiTraceIdStruct HiTraceChainBegin(const char* name, int flags) | +| | void End(const HiTraceId& id) | void HiTraceChainEnd(const HiTraceIdStruct* pId) | +| | HiTraceId GetId(); | HiTraceIdStruct HiTraceChainGetId() | +| | void SetId(const HiTraceId& id) | void HiTraceChainSetId(const HiTraceIdStruct* pId) | +| | void ClearId() | void HiTraceChainClearId() | +| | HiTraceId CreateSpan() | HiTraceIdStruct HiTraceChainCreateSpan() | +| | void Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | void HiTraceChainTracepoint(HiTraceTracepointType type, const HiTraceIdStruct* pId, const char* fmt, ...) | +| | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | void HiTraceChainTracepointEx(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceIdStruct* pId, const char* fmt, ...) | +| HiTraceId | HiTraceId(); | void HiTraceChainInitId(HiTraceIdStruct* pId) | +| | HiTraceId(const uint8_t* pIdArray, int len) | HiTraceIdStruct HiTraceChainBytesToId(const uint8_t* pIdArray, int len) | +| | bool IsValid() | int HiTraceChainIsValid(const HiTraceIdStruct* pId) | +| | bool IsFlagEnabled(HiTraceFlag flag) | int HiTraceChainIsFlagEnabled(const HiTraceIdStruct* pId, HiTraceFlag flag) | +| | void EnableFlag(HiTraceFlag flag) | void HiTraceChainEnableFlag(HiTraceIdStruct* pId, HiTraceFlag flag) | +| | int GetFlags() | int HiTraceChainGetFlags(const HiTraceIdStruct* pId) | +| | void SetFlags(int flags) | void HiTraceChainSetFlags(HiTraceIdStruct* pId, int flags) | +| | uint64_t GetChainId() | uint64_t HiTraceChainGetChainId(const HiTraceIdStruct* pId) | +| | void SetChainId(uint64_t chainId) | void HiTraceChainSetChainId(HiTraceIdStruct* pId, uint64_t chainId) | +| | uint64_t GetSpanId() | uint64_t HiTraceChainGetSpanId(const HiTraceIdStruct* pId) | +| | void SetSpanId(uint64_t spanId) | void HiTraceChainSetSpanId(HiTraceIdStruct* pId, uint64_t spanId) | +| | uint64_t GetParentSpanId() | uint64_t HiTraceChainGetParentSpanId(const HiTraceIdStruct* pId) | +| | void SetParentSpanId(uint64_t parentSpanId) | void HiTraceChainSetParentSpanId(HiTraceIdStruct* pId, uint64_t parentSpanId) | +| | int ToBytes(uint8_t* pIdArray, int len) | int HiTraceChainIdToBytes(const HiTraceIdStruct_ pId, uint8_t* pIdArray, int len) | ### 接口功能参数 - **表2** C++接口说明函数参数和功能 + **表2** 跟踪标志组合类型枚举 + +| **名称** | **值** | **说明** | +| -------- | -------- | -------- | +| HITRACE_FLAG_DEFAULT | 0 | 缺省标志。 | +| HITRACE_FLAG_INCLUDE_ASYNC | 1 | 异步调用标志。启动跟踪时,缺省只跟踪同步调用。设置该标志,同时跟踪同步、异步调用。 | +| HITRACE_FLAG_DONOT_CREATE_SPAN | 1 << 1 | 无分支标志。启动跟踪时,在同步、异步调用时缺省自动创建分支信息。设置该标志,指示不创建分支。 | +| HITRACE_FLAG_TP_INFO | 1 << 2 | 埋点标志。启动跟踪式时,缺省不进行埋点。调试场景下设置该标志,在同步、异步调用的收发侧自动埋点,输出埋点信息和时间戳。收发埋点按照client、server分为client send(CS)、server receive(SR)、server send(SS)、client receive(CR)四类信息。一次同步调用输出CS/SR/SS/CR,一次异步调用输出CS/SR/SS三个埋点信息。 | +| HITRACE_FLAG_NO_BE_INFO | 1 << 3 | 无起始结束标志。启动跟踪时,缺省打印启动及结束跟踪信息。设置该标志,指示不打印启动及结束跟踪信息。 | +| HITRACE_FLAG_DONOT_ENABLE_LOG | 1 << 4 | 日志关联标志。设置该标志,指示隐藏日志中的跟踪信息。 | +| HITRACE_FLAG_FAULT_TRIGGER | 1 << 5 | 故障触发标志。预置标志,暂时没有作用。 | +| HITRACE_FLAG_D2D_TP_INFO | 1 << 6 | 设备间埋点标志。TP_INFO的一个子集,设置该标志,只进行设备间的调用埋点。 | + + **表3** 跟踪埋点类型枚举 + +| **名称** | **值** | **说明** | +| -------- | -------- | -------- | +| HITRACE_TP_CS | 0 | 客户端发送类型,标识client侧的发送埋点。 | +| HITRACE_TP_CR | 1 | 客户端接收类型,标识client侧的接收埋点。 | +| HITRACE_TP_SS | 2 | 服务端发送类型,标识server侧的发送埋点。 | +| HITRACE_TP_SR | 3 | 服务端接收类型,标识server侧的接收埋点。 | +| HITRACE_TP_GENERAL | 4 | 一般类型,标识CS、CR、SS、SR四种场景之外的埋点。| + + **表4** 跟踪通信类型枚举 + +| **名称** | **值** | **说明** | +| -------- | -------- | -------- | +| HITRACE_CM_DEFAULT | 0 | 缺省通信类型 | +| HITRACE_CM_THREAD | 1 | 线程间通信类型 | +| HITRACE_CM_PROCESS | 2 | 进程间通信类型 | +| HITRACE_CM_DEVICE | 3 | 设备间通信类型 | + + **表5** C++接口说明函数参数和功能 | **类** | **方法** | **描述** | | -------- | -------- | -------- | -| HiTraceChain | HiTraceId Begin(const std::string& name, int flags) | 功能:启动HiTraceChain跟踪、生成HiTraceId对象并设置到当前线程TLS中。
输入参数:
- name:业务流程名称。
- flags:跟踪指示位,可以组合使用,具体含义为:
  - HITRACE_FLAG_INCLUDE_ASYNC:同时跟踪同步调用和异步调用,缺省只跟踪同步调用。
  - HITRACE_FLAG_DONOT_CREATE_SPAN:不创建子分支,缺省创建子分支。
  - HITRACE_FLAG_TP_INFO:输出tracepoint信息,缺省不输出。
  - HITRACE_FLAG_NO_BE_INFO:不输出起始、结束信息,缺省输出。
  - HITRACE_FLAG_DONOT_ENABLE_LOG:不与日志关联输出,缺省关联。
  - HITRACE_FLAG_FAULT_TRIGGER:故障触发的跟踪,缺省为正常启动的。
  - HITRACE_FLAG_D2D_TP_INFO:输出设备间tracepoint信息,缺省不输出。
  - HITRACE_FLAG_DEFAULT: 缺省标志。
- 输出参数:无
- 返回值:启动跟踪超过返回有效HiTraceId对象,否则返回无效对象。
注意:嵌套启动跟踪时,内层启动调用返回无效对象。 | -| | void End(const HiTraceId& id) | 功能:根据Begin返回的HiTraceId停止HiTraceChain跟踪;清除当前线程TLS中HiTraceId内容。
输入参数:
- id:HiTraceId对象。
输出参数:无。
返回值:无。 | -| | HiTraceId GetId(); | 功能:从当前线程TLS中获取HiTraceId对象。
输入参数:无。
输出参数:无。
返回值:当前线程上下文的HiTraceId对象。 | -| | void SetId(const HiTraceId& id) | 功能:设置HiTraceId对象内容到当前线程TLS中。
输入参数:
- id:HiTraceId对象。
输出参数:无。
返回值:无。 | -| | void ClearId() | 功能:清除当前线程TLS中的HiTraceId对象。
输入参数:无。
输出参数:无。
返回值:无。 | -| | HiTraceId CreateSpan() | 接口功能:获取当前HiTraceId对象中的分支ID。
输入参数:无。
输出参数:无。
返回值:当前分支ID。 | -| | void Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char\* fmt, ...) | 功能:根据埋点信息类型输出HiTraceChain埋点信息,包括时间戳、子分支HiTraceId对象信息。
输入参数:
- type:埋点信息类型,具体为
  - HITRACE_TP_CS:Client Send,同步/异步通信客户端发送信息。
  - HITRACE_TP_SR:Server Receive, 同步/异步通信服务端接收信息。
  - HITRACE_TP_SS:Server Send,同步通信服务端发送响应信息。
  - HITRACE_TP_CR:Client Receive,同步通信客户端接收响应信息。
  - HITRACE_TP_GENERAL:普通输出信息。
- id:当前子分支id。
- fmt:格式化变参描述字符串。
- args:变参。
输出参数:无。
返回值:无。 | -| | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id, const char\* fmt, ...) | 功能:根据通信模式、埋点信息类型输出HiTraceChain埋点信息,包括时间戳、子分支HiTraceId对象信息。
输入参数:
- mode:通信模式,具体为
  - HITRACE_CM_DEFAULT:未指定通信模式。
  - HITRACE_CM_THREAD:线程间通信。
  - HITRACE_CM_PROCESS:进程间通信。
  - HITRACE_CM_DEVICE:设备间通信。
- type:埋点信息类型,具体为
  - HITRACE_TP_CS:Client Send,同步/异步通信客户端发送信息。
  - HITRACE_TP_SR:Server Receive, 同步/异步通信服务端接收信息。
  - HITRACE_TP_SS:Server Send,同步通信服务端发送响应信息。
  - HITRACE_TP_CR:Client Receive,同步通信客户端接收响应信息。
  - HITRACE_TP_GENERAL:普通输出信息。
- id:当前子分支id。
- fmt:格式化变参描述字符串。
- args:变参。
输出参数:无。
返回值:无。 | +| HiTraceChain | HiTraceId Begin(const std::string& name, int flags) | 功能:启动HiTraceChain跟踪、生成HiTraceId对象并设置到当前线程TLS中。
输入参数:
- name:业务流程名称。
- flags:跟踪指示位,可以组合使用,具体说明请参考**表2** 跟踪标志组合类型枚举。
- 输出参数:无
- 返回值:启动跟踪超过返回有效HiTraceId对象,否则返回无效对象。
注意:嵌套启动跟踪时,内层启动调用返回无效对象。 | +| | void End(const HiTraceId& id) | 功能:根据Begin返回的HiTraceId停止HiTraceChain跟踪;清除当前线程TLS中HiTraceId内容。
输入参数:
- id:HiTraceId对象。
输出参数:无。
返回值:无。 | +| | HiTraceId GetId(); | 功能:从当前线程TLS中获取HiTraceId对象。
输入参数:无。
输出参数:无。
返回值:当前线程上下文的HiTraceId对象。 | +| | void SetId(const HiTraceId& id) | 功能:设置HiTraceId对象内容到当前线程TLS中。
输入参数:
- id:HiTraceId对象。
输出参数:无。
返回值:无。 | +| | void ClearId() | 功能:清除当前线程TLS中的HiTraceId对象。
输入参数:无。
输出参数:无。
返回值:无。 | +| | HiTraceId CreateSpan() | 接口功能:获取当前HiTraceId对象中的分支ID。
输入参数:无。
输出参数:无。
返回值:当前分支ID。 | +| | void Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | 功能:根据埋点信息类型输出HiTraceChain埋点信息,包括时间戳、子分支HiTraceId对象信息。
输入参数:
- type:埋点信息类型,具体说明请参考**表3** 跟踪埋点类型枚举。
- id:当前子分支id。
- fmt:格式化变参描述字符串。
- args:变参。
输出参数:无。
返回值:无。 | +| | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | 功能:根据通信模式、埋点信息类型输出HiTraceChain埋点信息,包括时间戳、子分支HiTraceId对象信息。
输入参数:
- mode:通信模式,具体说明请参考**表4** 跟踪通信类型枚举。
- type:埋点信息类型,具体说明请参考**表3** 跟踪埋点类型枚举。
- id:当前子分支id。
- fmt:格式化变参描述字符串。
- args:变参。
输出参数:无。
返回值:无。 | | HiTraceId | HiTraceId(); | 功能:缺省构造函数,生成无效HiTraceId对象。
输入参数:无。
输出参数:无。
返回值:无。 | -| | HiTraceId(const uint8_t\* pIdArray, int len) | 功能:构造函数,根据字节数组创建跟踪HiTraceId对象。
输入参数:
- pIdArray:字节数组指针。
- len:字节数组长度。
输出参数:无。
返回值:无。 | -| | bool IsValid() | 功能:HiTraceId对象是否有效。
输入参数:无。
输出参数:无。
返回值:true 有效;false 无效。 | -| | bool IsFlagEnabled(HiTraceFlag flag) | 功能:HiTraceId对象的某标志是否置位。
输入参数:
- flag:跟踪指示位,具体含义见Begin函数中的定义。
输出参数:无。
返回值:true 该标志置位;false 该标志未置位。 | -| | void EnableFlag(HiTraceFlag flag) | 功能:设置某跟踪标志位到HiTraceId对象中。
输入参数:
- flag:跟踪指示位,具体含义见Begin函数中的定义。
输出参数:无。
返回值:无。 | -| | int GetFlags() | 功能:获取HiTraceId对象中设置的标志位。
输入参数:无。
输出参数:无。
返回值:跟踪指示位组合,具体含义见Begin函数中的定义。 | -| | void SetFlags(int flags) | 功能:设置跟踪标志位到HiTraceId对象中。
输入参数:
- flags:跟踪指示位组合,具体含义见Begin函数中的定义。
输出参数:无。
返回值:无。 | -| | uint64_t GetChainId() | 功能:获取跟踪链ID。
输入参数:无。
输出参数:无。
返回值:跟踪链ID。 | -| | void SetChainId(uint64_t chainId) | 功能:设置跟踪链ID到HiTraceId对象中。
输入参数:
- chainId:跟踪链ID。
输出参数:无。
返回值:无。 | -| | uint64_t GetSpanId() | 接口功能:获取当前HiTraceId对象中的分支ID。
输入参数:无。
输出参数:无。
返回值:当前分支ID。 | -| | void SetSpanId(uint64_t spanId) | 功能:设置分支ID到HiTraceId对象中。
输入参数:
- spanId:分支ID。
输出参数:无。
返回值:无。 | -| | uint64_t GetParentSpanId() | 功能:获取当前HiTraceId对象中的父分支ID。
输入参数:无。
输出参数:无。
返回值:父分支ID。 | -| | void SetParentSpanId(uint64_t parentSpanId) | 功能:设置父分支ID到HiTraceId对象中。
输入参数:
- parentSpanId:父分支ID。
输出参数:无。
返回值:无。 | -| | int ToBytes(uint8_t\* pIdArray, int len) | 功能:将HiTraceId对象转换为字节数组,便于缓存或者通信传递。
输入参数:
- pIdArray:字节数组指针,数组长度至少为HITRACE_ID_LEN。
- len: 字节数组长度
输出参数:
- pIdArray:字节数组指针,对象有效时存储转换后的对象数据。
返回值:0 转换失败; &gt;0 有效对象转换数组长度。 | +| | HiTraceId(const uint8_t* pIdArray, int len) | 功能:构造函数,根据字节数组创建跟踪HiTraceId对象。
输入参数:
- pIdArray:字节数组指针。
- len:字节数组长度。
输出参数:无。
返回值:无。 | +| | bool IsValid() | 功能:HiTraceId对象是否有效。
输入参数:无。
输出参数:无。
返回值:true 有效;false 无效。 | +| | bool IsFlagEnabled(HiTraceFlag flag) | 功能:HiTraceId对象的某标志是否置位。
输入参数:
- flag:跟踪指示位,具体含义见Begin函数中的定义。
输出参数:无。
返回值:true 该标志置位;false 该标志未置位。 | +| | void EnableFlag(HiTraceFlag flag) | 功能:设置某跟踪标志位到HiTraceId对象中。
输入参数:
- flag:跟踪指示位,具体含义见Begin函数中的定义。
输出参数:无。
返回值:无。 | +| | int GetFlags() | 功能:获取HiTraceId对象中设置的标志位。
输入参数:无。
输出参数:无。
返回值:跟踪指示位组合,具体含义见Begin函数中的定义。 | +| | void SetFlags(int flags) | 功能:设置跟踪标志位到HiTraceId对象中。
输入参数:
- flags:跟踪指示位组合,具体含义见Begin函数中的定义。
输出参数:无。
返回值:无。 | +| | uint64_t GetChainId() | 功能:获取跟踪链ID。
输入参数:无。
输出参数:无。
返回值:跟踪链ID。 | +| | void SetChainId(uint64_t chainId) | 功能:设置跟踪链ID到HiTraceId对象中。
输入参数:
- chainId:跟踪链ID。
输出参数:无。
返回值:无。 | +| | uint64_t GetSpanId() | 接口功能:获取当前HiTraceId对象中的分支ID。
输入参数:无。
输出参数:无。
返回值:当前分支ID。 | +| | void SetSpanId(uint64_t spanId) | 功能:设置分支ID到HiTraceId对象中。
输入参数:
- spanId:分支ID。
输出参数:无。
返回值:无。 | +| | uint64_t GetParentSpanId() | 功能:获取当前HiTraceId对象中的父分支ID。
输入参数:无。
输出参数:无。
返回值:父分支ID。 | +| | void SetParentSpanId(uint64_t parentSpanId) | 功能:设置父分支ID到HiTraceId对象中。
输入参数:
- parentSpanId:父分支ID。
输出参数:无。
返回值:无。 | +| | int ToBytes(uint8_t* pIdArray, int len) | 功能:将HiTraceId对象转换为字节数组,便于缓存或者通信传递。
输入参数:
- pIdArray:字节数组指针,数组长度至少为HITRACE_ID_LEN。
- len: 字节数组长度
输出参数:
- pIdArray:字节数组指针,对象有效时存储转换后的对象数据。
返回值:0 转换失败; &gt;0 有效对象转换数组长度。 | ## 通信调用处理 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md index c4ac1bf5503818d94237cf12de8f3ce7fe91ce63..58a4e82fea85f151a2101dd586adec0c520bed21 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md @@ -1,359 +1,353 @@ -# HiTraceMeter概述 - -## 简介 - -HiTraceMeter在OpenHarmony中,为开发者提供业务流程调用链跟踪的维测接口。通过使用该接口所提供的功能,可以帮助开发者迅速获取指定业务流程调用链的运行日志、定位跨设备/跨进程/跨线程的故障问题。HiTraceMeter用来支持用户态的打点,采集用户态和内核态的trace数据,从而进行性能跟踪与分析的系统。 - -## 基本概念 - -HiTraceMeter系统主要分为三部分: -- JS/C++应用打点API; -- Trace数据采集命令行工具; -- Trace数据图形分析工具。 - -其中,前两者运行在设备端侧,图形工具运行在PC主机侧。打点API部分提供了C++和JS接口,供开发过程中打点使用,打点用于产生Trace数据流,是抓Trace数据的基础条件。 - -命令行工具用于采集Trace数据,用来抓取Trace数据流并保存到文本文件。 - -Trace数据分析可以在图形工具中人工分析,也可以使用分析脚本自动化分析,Trace分析工具以Trace命令行工具的采集结果数据文件为输入。 - - HiTraceMeter跟踪数据使用类别分类,类别分类称作Trace Tag或Trace Category,一般一个端侧软件子系统对应一个Tag。该Tag在打点API中以类别Tag参数传入。Trace命令行工具采集跟踪数据时,只采集Tag类别选项指定的跟踪数据。应用程序跟踪数据标签都是属于APP Tag,从而JS接口不需要输入tag参数。目前HiTraceMeter支持的Trace Tag表如下(可在hitrace_meter.h [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h) 中查看): - -```cpp -constexpr uint64_t HITRACE_TAG_NEVER = 0; // This tag is never enabled. -constexpr uint64_t HITRACE_TAG_ALWAYS = (1ULL << 0); // This tag is always enabled. -constexpr uint64_t HITRACE_TAG_DLP_CREDENTIAL = (1ULL << 21); // This tag is dlp credential service. -constexpr uint64_t HITRACE_TAG_ACCESS_CONTROL = (1ULL << 22); // This tag is access control tag. -constexpr uint64_t HITRACE_TAG_NET = (1ULL << 23); // Net tag. -constexpr uint64_t HITRACE_TAG_NWEB = (1ULL << 24); // NWeb tag. -constexpr uint64_t HITRACE_TAG_HUKS = (1ULL << 25); // This tag is huks. -constexpr uint64_t HITRACE_TAG_USERIAM = (1ULL << 26); // This tag is useriam. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_AUDIO = (1ULL << 27); // Distributed audio tag. -constexpr uint64_t HITRACE_TAG_DLSM = (1ULL << 28); // device security level tag. -constexpr uint64_t HITRACE_TAG_FILEMANAGEMENT = (1ULL << 29); // filemanagement tag. -constexpr uint64_t HITRACE_TAG_OHOS = (1ULL << 30); // OHOS generic tag. -constexpr uint64_t HITRACE_TAG_ABILITY_MANAGER = (1ULL << 31); // Ability Manager tag. -constexpr uint64_t HITRACE_TAG_ZCAMERA = (1ULL << 32); // Camera module tag. -constexpr uint64_t HITRACE_TAG_ZMEDIA = (1ULL << 33); // Media module tag. -constexpr uint64_t HITRACE_TAG_ZIMAGE = (1ULL << 34); // Image module tag. -constexpr uint64_t HITRACE_TAG_ZAUDIO = (1ULL << 35); // Audio module tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTEDDATA = (1ULL << 36); // Distributeddata manager module tag. -constexpr uint64_t HITRACE_TAG_MDFS = (1ULL << 37); // Mobile distributed file system tag. -constexpr uint64_t HITRACE_TAG_GRAPHIC_AGP = (1ULL << 38); // Graphic module tag. -constexpr uint64_t HITRACE_TAG_ACE = (1ULL << 39); // ACE development framework tag. -constexpr uint64_t HITRACE_TAG_NOTIFICATION = (1ULL << 40); // Notification module tag. -constexpr uint64_t HITRACE_TAG_MISC = (1ULL << 41); // Notification module tag. -constexpr uint64_t HITRACE_TAG_MULTIMODALINPUT = (1ULL << 42); // Multi modal module tag. -constexpr uint64_t HITRACE_TAG_SENSORS = (1ULL << 43); // Sensors mudule tag. -constexpr uint64_t HITRACE_TAG_MSDP = (1ULL << 44); // Multimodal Sensor Data Platform module tag. -constexpr uint64_t HITRACE_TAG_DSOFTBUS = (1ULL << 45); // Distributed Softbus tag. -constexpr uint64_t HITRACE_TAG_RPC = (1ULL << 46); // RPC and IPC tag. -constexpr uint64_t HITRACE_TAG_ARK = (1ULL << 47); // ARK tag. -constexpr uint64_t HITRACE_TAG_WINDOW_MANAGER = (1ULL << 48); // window manager tag. -constexpr uint64_t HITRACE_TAG_ACCOUNT_MANAGER = (1ULL << 49); // account manager tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_SCREEN = (1ULL << 50); // Distributed screen tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_CAMERA = (1ULL << 51); // Distributed camera tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_HARDWARE_FWK = (1ULL << 52); // Distributed hardware fwk tag. -constexpr uint64_t HITRACE_TAG_GLOBAL_RESMGR = (1ULL << 53); // Global resource manager tag. -constexpr uint64_t HITRACE_TAG_DEVICE_MANAGER = (1ULL << 54); // Distributed hardware devicemanager tag. -constexpr uint64_t HITRACE_TAG_SAMGR = (1ULL << 55); // SA tag. -constexpr uint64_t HITRACE_TAG_POWER = (1ULL << 56); // power manager tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_SCHEDULE = (1ULL << 57); // Distributed schedule tag. -constexpr uint64_t HITRACE_TAG_DEVICE_PROFILE = (1ULL << 58); // device profile tag. -constexpr uint64_t HITRACE_TAG_DISTRIBUTED_INPUT = (1ULL << 59); // Distributed input tag. -constexpr uint64_t HITRACE_TAG_BLUETOOTH = (1ULL << 60); // bluetooth tag. -constexpr uint64_t HITRACE_TAG_ACCESSIBILITY_MANAGER = (1ULL << 61); // accessibility manager tag. -constexpr uint64_t HITRACE_TAG_APP = (1ULL << 62); // App tag. - -constexpr uint64_t HITRACE_TAG_LAST = HITRACE_TAG_APP; -constexpr uint64_t HITRACE_TAG_NOT_READY = (1ULL << 63); // Reserved for initialization. -constexpr uint64_t HITRACE_TAG_VALID_MASK = ((HITRACE_TAG_LAST - 1) | HITRACE_TAG_LAST); -``` - -## 实现原理 - -HiTraceMeter主要提供抓取用户态和内核态Trace数据的命令行工具,提供用户态打点的innerkits接口(c++)和kits接口(js),HiTraceMeter基于内核ftrace提供的用户态打点的扩展,利用ftrace的trace_marker节点,将用户空间通过打点接口写入的数据写进内核循环buffer缓冲区。其基本架构图如下: - - - -![输入图片说明](figures/HiTraceMeter.png) - - - - -## 约束与限制 - -- HiTraceMeter所有功能与接口的实现都依赖于内核提供的ftrace功能,ftrace 是内核提供的一个 framework,采用 plugin 的方式支持开发人员添加更多种类的 trace 功能,因此使用HiTraceMeter之前要使能 ftrace,否则HiTraceMeter的功能无法使用(目前大部分Linux内核默认使能了ftrace,关于ftrace的详细介绍可查看内核ftrace相关资料 - [ftrace相关资料](https://blog.csdn.net/Luckiers/article/details/124646205) )。 -- HiTraceMeter仅限小型系统、标准系统下使用。 - - - -# HiTraceMeter开发指导 - -HiTraceMeter分为JS/C++应用打点API与数据采集命令行工具hitrace,下面分别介绍接口和命令行工具。 - - - - -## 场景介绍 - -在实际开发过程中,开发者可能会遇到app卡顿或者在代码调试过程中需要查看代码调用流程,HiTraceMeter接口提供了相应的接口来跟踪程序延时和代码调用流程,分析性能问题。 - -## 接口说明 - -C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开发者可以略过本节。标准系统上接口描述如下(hitrace_meter.h [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h) ): - -**表 1** 同步接口 - -| Sync 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参数用于限流,使用默认值即可。 - -**表 2** 异步接口 - -| Async trace | 功能描述 |参数说明 | -| ------------------------------------------------------------ | ------------- |------------- | -| 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。 | - - - -异步接口StartAsyncTrace和FinishAsyncTrace的跟踪数据匹配时,使用参数中的value和taskId配对匹配,可以不按顺序使用,主要用于异步场景。在C++程序中,使用异步跟踪的场景很少。 - -**表 3** 计数器接口 - -| Counter Trace | 功能描述 |参数说明 | -| ------------------------------------------------------------ | --------- |--------- | -| void CountTrace(uint64_t label, const std::string& name, int64_t); | 计数trace |label: Trace category。
name: Trace的名称,IDE中会以此字段展示这段Trace。 | - - -## 开发步骤 -1. 编译依赖添加,需要修改的编译配置文件base\hiviewdfx\hitrace\cmd\BUILD.gn 。 - - ``` - external_deps = [ "hitrace_native:hitrace_meter"] - ``` -2. 头文件依赖添加。 - - ```cpp - #include "hitrace_meter.h"//接口函数定义头文件 - ``` - -3. 接口调用,将需要跟踪的Trace value传入参数,在shell中执行hitrace命令后会自动抓取Trace数据,抓到的Trace数据中包括了函数调用过程以及调用过程消耗的内存和时间,可用于分析代码调用流程,代码性能问题。 - - - ```cpp - - CountTrace(label, "count number", 2000); // 整数跟踪 - - StartTrace(label, "func1Trace", -1); // func1Start的跟踪起始点 - - FinishTrace(label); // func1Trace的结束点 - - StartAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的开始点 - - FinishAsyncTrace(label, "asyncTrace2", 3456); // 异步asyncTrace2的结束点 - ``` - -4. 使用方法,打点编译部署完成后,运行下面命令行来抓取Trace。然后在端侧shell里运行应用,可以抓取到Trace数据。 - - ``` - hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace - ``` - - 抓取之后的数据可以在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。 - -1. 编写测试代码hitrace_example.cpp( [hitrace_example.cpp](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/cmd/example/hitrace_example.cpp) ),将使用到的接口加入代码: - - ```cpp - int main() - { - thread t1(ThreadFunc1); - t1.join(); - - StartTrace(LABEL, "testStart"); - sleep(SLEEP_ONE_SECOND); - - StartTrace(LABEL, "funcAStart", SLEEP_ONE_SECOND); // 打印起始点 - FuncA(); - FinishTrace(LABEL); - sleep(SLEEP_TWO_SECOND); - - thread t2(ThreadFunc2); - t2.join(); - - StartTrace(LABEL, "funcBStart", SLEEP_TWO_SECOND); - FuncB(); - FinishTrace(LABEL);// 打印结束点 - sleep(SLEEP_TWO_SECOND); - - sleep(SLEEP_ONE_SECOND); - FinishTrace(LABEL); - FuncC(); - - return 0; - } - ``` - -2. 修改gn编译文件并编译,编译配置文件路径base\hiviewdfx\hitrace\cmd\BUILD.gn 。 - - ``` - 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", - ":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 - <...>-1650 (-------) [001] .... 332.197640: tracing_mark_write: B|1650|H:testStart - <...>-1650 (-------) [001] .... 333.198018: tracing_mark_write: B|1650|H:funcAStart - <...>-1650 (-------) [001] .... 334.198507: tracing_mark_write: E|1650| - <...>-1654 (-------) [003] .... 341.201673: tracing_mark_write: F|1650|H:testAsync 111 - <...>-1650 (-------) [001] .... 341.202168: tracing_mark_write: B|1650|H:funcBStart - <...>-1650 (-------) [001] .... 343.202557: tracing_mark_write: E|1650| - <...>-1650 (-------) [001] .... 346.203178: tracing_mark_write: E|1650| - <...>-1650 (-------) [001] .... 346.203457: tracing_mark_write: C|1650|H:count number 1 - <...>-1650 (-------) [001] .... 347.203818: tracing_mark_write: C|1650|H:count number 2 - <...>-1650 (-------) [001] .... 348.204207: tracing_mark_write: C|1650|H:count number 3 - <...>-1650 (-------) [001] .... 349.204473: tracing_mark_write: C|1650|H:count number 4 - <...>-1650 (-------) [001] .... 350.204851: tracing_mark_write: C|1650|H:count number 5 - <...>-1655 (-------) [001] .... 365.944658: tracing_mark_write: trace_event_clock_sync: realtime_ts=1502021460925 - <...>-1655 (-------) [001] .... 365.944686: tracing_mark_write: trace_event_clock_sync: parent_ts=365.944641 - ``` - - - -# HiTraceMeter命令行工具使用指导 - -HiTraceMeter提供了可执行的二进制程序hitrace,设备刷openharmony后直接在shell中运行以下命令,抓取内核运行的数据,当前支持的操作如下: - -**表 4** 命令行列表 - -| Option | Description | -| ------------------------------ | ------------------------------------------------------------ | -| -h,--help | 查看option帮助 | -| -b n,--buffer_size n | 指定n(KB)内存大小用于存取trace日志,默认2048KB | -| -t n,--time n | 用来指定trace运行的时间(单位:s),取决于需要分析过程的时间 | -| --trace_clock clock | trace输出的时钟类型,一般设备支持boot、global、mono、uptime、perf等,默认为boot | -| --trace_begin | 启动抓trace | -| --trace_dump | 将数据输出到指定位置(默认控制台) | -| --trace_finish | 停止抓trace,并将数据输出到指定位置(默认控制台) | -| -l,--list_categories | 输出手机能支持的trace模块 | -| --overwrite | 当缓冲区满的时候,将丢弃最新的信息。(默认丢弃最老的日志) | -| -o filename,--output filename | 指定输出的目标文件名称 | -| -z | 抓取trace后进行压缩 | - -以下是常用hitrace命令示例,供开发者参考: - -- 查询支持的label。 - - ``` - hitrace -l - ``` - - 或者 - - ``` - hitrace --list_categories - ``` - - -- 设置4M缓存,抓取10秒,抓取label为ability的trace信息。 - - ``` - hitrace -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace - ``` - - -- 设置trace的输出时钟为mono。 - - ``` - hitrace --trace_clock mono -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace - ``` - - -- 抓取trace后进行压缩。 - - ``` - hitrace -z -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace - ``` - - - -# 常见问题 - -### hitrace抓数据不全或者没抓到数据 - -#### 现象描述 - - 执行hitrace命令抓数据不全或者没抓到数据。 - -#### 解决方法 - - 参数-t 时间设置过小或者-b缓冲区buffer设置过小导致数据丢失,可设置-t 60,-b 204800扩大抓trace时间和缓冲区buffer解决。 - - - -# 参考 - -更多关于HiTraceMeter的详细内容请参考:[hiviewdfx_hitrace: A Lightweight Distributed Tracing | 轻量级的分布式调用链跟踪 (gitee.com)](https://gitee.com/openharmony/hiviewdfx_hitrace) 。 - +# HiTraceMeter概述 + +## 简介 + +HiTraceMeter在OpenHarmony中,为开发者提供业务流程调用链跟踪的维测接口。通过使用该接口所提供的功能,可以帮助开发者迅速获取指定业务流程调用链的运行日志、定位跨设备/跨进程/跨线程的故障问题。HiTraceMeter用来支持用户态的打点,采集用户态和内核态的trace数据,从而进行性能跟踪与分析的系统。 + +## 基本概念 + +HiTraceMeter系统主要分为三部分: + +- JS/C++应用打点API; +- Trace数据采集命令行工具; +- Trace数据图形分析工具。 + +其中,前两者运行在设备端侧,图形工具运行在PC主机侧。打点API部分提供了C++和JS接口,供开发过程中打点使用,打点用于产生Trace数据流,是抓Trace数据的基础条件。 + +命令行工具用于采集Trace数据,用来抓取Trace数据流并保存到文本文件。 + +Trace数据分析可以在图形工具中人工分析,也可以使用分析脚本自动化分析,Trace分析工具以Trace命令行工具的采集结果数据文件为输入。 + + HiTraceMeter跟踪数据使用类别分类,类别分类称作Trace Tag或Trace Category,一般一个端侧软件子系统对应一个Tag。该Tag在打点API中以类别Tag参数传入。Trace命令行工具采集跟踪数据时,只采集Tag类别选项指定的跟踪数据。应用程序跟踪数据标签都是属于APP Tag,从而JS接口不需要输入tag参数。目前HiTraceMeter支持的Trace Tag表如下(可在hitrace_meter.h [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h) 中查看): + +```cpp +constexpr uint64_t HITRACE_TAG_NEVER = 0; // This tag is never enabled. +constexpr uint64_t HITRACE_TAG_ALWAYS = (1ULL << 0); // This tag is always enabled. +constexpr uint64_t HITRACE_TAG_DLP_CREDENTIAL = (1ULL << 21); // This tag is dlp credential service. +constexpr uint64_t HITRACE_TAG_ACCESS_CONTROL = (1ULL << 22); // This tag is access control tag. +constexpr uint64_t HITRACE_TAG_NET = (1ULL << 23); // Net tag. +constexpr uint64_t HITRACE_TAG_NWEB = (1ULL << 24); // NWeb tag. +constexpr uint64_t HITRACE_TAG_HUKS = (1ULL << 25); // This tag is huks. +constexpr uint64_t HITRACE_TAG_USERIAM = (1ULL << 26); // This tag is useriam. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_AUDIO = (1ULL << 27); // Distributed audio tag. +constexpr uint64_t HITRACE_TAG_DLSM = (1ULL << 28); // device security level tag. +constexpr uint64_t HITRACE_TAG_FILEMANAGEMENT = (1ULL << 29); // filemanagement tag. +constexpr uint64_t HITRACE_TAG_OHOS = (1ULL << 30); // OHOS generic tag. +constexpr uint64_t HITRACE_TAG_ABILITY_MANAGER = (1ULL << 31); // Ability Manager tag. +constexpr uint64_t HITRACE_TAG_ZCAMERA = (1ULL << 32); // Camera module tag. +constexpr uint64_t HITRACE_TAG_ZMEDIA = (1ULL << 33); // Media module tag. +constexpr uint64_t HITRACE_TAG_ZIMAGE = (1ULL << 34); // Image module tag. +constexpr uint64_t HITRACE_TAG_ZAUDIO = (1ULL << 35); // Audio module tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTEDDATA = (1ULL << 36); // Distributeddata manager module tag. +constexpr uint64_t HITRACE_TAG_MDFS = (1ULL << 37); // Mobile distributed file system tag. +constexpr uint64_t HITRACE_TAG_GRAPHIC_AGP = (1ULL << 38); // Graphic module tag. +constexpr uint64_t HITRACE_TAG_ACE = (1ULL << 39); // ACE development framework tag. +constexpr uint64_t HITRACE_TAG_NOTIFICATION = (1ULL << 40); // Notification module tag. +constexpr uint64_t HITRACE_TAG_MISC = (1ULL << 41); // Notification module tag. +constexpr uint64_t HITRACE_TAG_MULTIMODALINPUT = (1ULL << 42); // Multi modal module tag. +constexpr uint64_t HITRACE_TAG_SENSORS = (1ULL << 43); // Sensors mudule tag. +constexpr uint64_t HITRACE_TAG_MSDP = (1ULL << 44); // Multimodal Sensor Data Platform module tag. +constexpr uint64_t HITRACE_TAG_DSOFTBUS = (1ULL << 45); // Distributed Softbus tag. +constexpr uint64_t HITRACE_TAG_RPC = (1ULL << 46); // RPC and IPC tag. +constexpr uint64_t HITRACE_TAG_ARK = (1ULL << 47); // ARK tag. +constexpr uint64_t HITRACE_TAG_WINDOW_MANAGER = (1ULL << 48); // window manager tag. +constexpr uint64_t HITRACE_TAG_ACCOUNT_MANAGER = (1ULL << 49); // account manager tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_SCREEN = (1ULL << 50); // Distributed screen tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_CAMERA = (1ULL << 51); // Distributed camera tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_HARDWARE_FWK = (1ULL << 52); // Distributed hardware fwk tag. +constexpr uint64_t HITRACE_TAG_GLOBAL_RESMGR = (1ULL << 53); // Global resource manager tag. +constexpr uint64_t HITRACE_TAG_DEVICE_MANAGER = (1ULL << 54); // Distributed hardware devicemanager tag. +constexpr uint64_t HITRACE_TAG_SAMGR = (1ULL << 55); // SA tag. +constexpr uint64_t HITRACE_TAG_POWER = (1ULL << 56); // power manager tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_SCHEDULE = (1ULL << 57); // Distributed schedule tag. +constexpr uint64_t HITRACE_TAG_DEVICE_PROFILE = (1ULL << 58); // device profile tag. +constexpr uint64_t HITRACE_TAG_DISTRIBUTED_INPUT = (1ULL << 59); // Distributed input tag. +constexpr uint64_t HITRACE_TAG_BLUETOOTH = (1ULL << 60); // bluetooth tag. +constexpr uint64_t HITRACE_TAG_ACCESSIBILITY_MANAGER = (1ULL << 61); // accessibility manager tag. +constexpr uint64_t HITRACE_TAG_APP = (1ULL << 62); // App tag. + +constexpr uint64_t HITRACE_TAG_LAST = HITRACE_TAG_APP; +constexpr uint64_t HITRACE_TAG_NOT_READY = (1ULL << 63); // Reserved for initialization. +constexpr uint64_t HITRACE_TAG_VALID_MASK = ((HITRACE_TAG_LAST - 1) | HITRACE_TAG_LAST); +``` + +## 实现原理 + +HiTraceMeter主要提供抓取用户态和内核态Trace数据的命令行工具,提供用户态打点的innerkits接口(c++)和kits接口(js),HiTraceMeter基于内核ftrace提供的用户态打点的扩展,利用ftrace的trace_marker节点,将用户空间通过打点接口写入的数据写进内核循环buffer缓冲区。其基本架构图如下: + + + +![输入图片说明](figures/HiTraceMeter.png) + + + +## 约束与限制 + +- HiTraceMeter所有功能与接口的实现都依赖于内核提供的ftrace功能,ftrace 是内核提供的一个 framework,采用 plugin 的方式支持开发人员添加更多种类的 trace 功能,因此使用HiTraceMeter之前要使能 ftrace,否则HiTraceMeter的功能无法使用(目前大部分Linux内核默认使能了ftrace,关于ftrace的详细介绍可查看内核ftrace相关资料 + [ftrace相关资料](https://blog.csdn.net/Luckiers/article/details/124646205) )。 +- HiTraceMeter仅限小型系统、标准系统下使用。 + + + +# HiTraceMeter开发指导 + +HiTraceMeter分为JS/C++应用打点API与数据采集命令行工具hitrace,下面分别介绍接口和命令行工具。 + + + +## 场景介绍 + +在实际开发过程中,开发者可能会遇到app卡顿或者在代码调试过程中需要查看代码调用流程,HiTraceMeter接口提供了相应的接口来跟踪程序延时和代码调用流程,分析性能问题。 + +## 接口说明 + +C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开发者可以略过本节。标准系统上接口描述如下(hitrace_meter.h [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h) ): + +**表 1** 同步接口 + +| Sync 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参数用于限流,使用默认值即可。 + +**表 2** 异步接口 + +| Async trace | 功能描述 | 参数说明 | +| ------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------- | +| 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。 | + + + +异步接口StartAsyncTrace和FinishAsyncTrace的跟踪数据匹配时,使用参数中的value和taskId配对匹配,可以不按顺序使用,主要用于异步场景。在C++程序中,使用异步跟踪的场景很少。 + +**表 3** 计数器接口 + +| Counter Trace | 功能描述 | 参数说明 | +| ------------------------------------------------------------------ | ------- | -------------------------------------------------------------- | +| void CountTrace(uint64_t label, const std::string& name, int64_t); | 计数trace | label: Trace category。
name: Trace的名称,IDE中会以此字段展示这段Trace。 | + +## 开发步骤 + +1. 编译依赖添加,需要修改的编译配置文件base\hiviewdfx\hitrace\cmd\BUILD.gn 。 + + ``` + external_deps = [ "hitrace_native:hitrace_meter"] + ``` + +2. 头文件依赖添加。 + + ```cpp + #include "hitrace_meter.h"//接口函数定义头文件 + ``` + +3. 接口调用,将需要跟踪的Trace value传入参数,目前HiTraceMeter支持的Trace Tag在基本概念hitrace_meter.h中都已列出,我们以OHOS这个Tag为例,假设我们需要获取func1,func2函数的Trace数据,参考下面实例,在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的结束点 + + StartAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的开始点 + FinishAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的结束点 + + return 0; + } + ``` + +4. 使用方法,打点编译部署完成后,运行下面命令行来抓取Trace。然后在端侧shell里运行应用,可以抓取到Trace数据。 + + ``` + hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace + ``` + + 抓取之后的数据可以在smartperf中"Open trace file"或者直接拖入图形区打开,关于smartperf的详细介绍可查看 [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf) 。 + +## 调测验证 + +以下为一个demo调试过程,该demo使用了同步接口中的StartTrace和FinishTrace。 + +1. 编写测试代码hitrace_example.cpp( [hitrace_example.cpp](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/cmd/example/hitrace_example.cpp) ),将使用到的接口加入代码: + + ```cpp + int main() + { + thread t1(ThreadFunc1); + t1.join(); + + StartTrace(LABEL, "testStart"); + sleep(SLEEP_ONE_SECOND); + + StartTrace(LABEL, "funcAStart", SLEEP_ONE_SECOND); // 打印起始点 + FuncA(); + FinishTrace(LABEL); + sleep(SLEEP_TWO_SECOND); + + thread t2(ThreadFunc2); + t2.join(); + + StartTrace(LABEL, "funcBStart", SLEEP_TWO_SECOND); + FuncB(); + FinishTrace(LABEL);// 打印结束点 + sleep(SLEEP_TWO_SECOND); + + sleep(SLEEP_ONE_SECOND); + FinishTrace(LABEL); + FuncC(); + + return 0; + } + ``` + +2. 修改gn编译文件并编译,编译配置文件路径base\hiviewdfx\hitrace\cmd\BUILD.gn 。 + + ``` + 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", + ":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 + <...>-1650 (-------) [001] .... 332.197640: tracing_mark_write: B|1650|H:testStart + <...>-1650 (-------) [001] .... 333.198018: tracing_mark_write: B|1650|H:funcAStart + <...>-1650 (-------) [001] .... 334.198507: tracing_mark_write: E|1650| + <...>-1654 (-------) [003] .... 341.201673: tracing_mark_write: F|1650|H:testAsync 111 + <...>-1650 (-------) [001] .... 341.202168: tracing_mark_write: B|1650|H:funcBStart + <...>-1650 (-------) [001] .... 343.202557: tracing_mark_write: E|1650| + <...>-1650 (-------) [001] .... 346.203178: tracing_mark_write: E|1650| + <...>-1650 (-------) [001] .... 346.203457: tracing_mark_write: C|1650|H:count number 1 + <...>-1650 (-------) [001] .... 347.203818: tracing_mark_write: C|1650|H:count number 2 + <...>-1650 (-------) [001] .... 348.204207: tracing_mark_write: C|1650|H:count number 3 + <...>-1650 (-------) [001] .... 349.204473: tracing_mark_write: C|1650|H:count number 4 + <...>-1650 (-------) [001] .... 350.204851: tracing_mark_write: C|1650|H:count number 5 + <...>-1655 (-------) [001] .... 365.944658: tracing_mark_write: trace_event_clock_sync: realtime_ts=1502021460925 + <...>-1655 (-------) [001] .... 365.944686: tracing_mark_write: trace_event_clock_sync: parent_ts=365.944641 + ``` + + + +# HiTraceMeter命令行工具使用指导 + +HiTraceMeter提供了可执行的二进制程序hitrace,设备刷openharmony后直接在shell中运行以下命令,抓取内核运行的数据,当前支持的操作如下: + +**表 4** 命令行列表 + +| Option | Description | +| ----------------------------- | -------------------------------------------------------- | +| -h,--help | 查看option帮助 | +| -b n,--buffer_size n | 指定n(KB)内存大小用于存取trace日志,默认2048KB | +| -t n,--time n | 用来指定trace运行的时间(单位:s),取决于需要分析过程的时间 | +| --trace_clock clock | trace输出的时钟类型,一般设备支持boot、global、mono、uptime、perf等,默认为boot | +| --trace_begin | 启动抓trace | +| --trace_dump | 将数据输出到指定位置(默认控制台) | +| --trace_finish | 停止抓trace,并将数据输出到指定位置(默认控制台) | +| -l,--list_categories | 输出手机能支持的trace模块 | +| --overwrite | 当缓冲区满的时候,将丢弃最新的信息。(默认丢弃最老的日志) | +| -o filename,--output filename | 指定输出的目标文件名称 | +| -z | 抓取trace后进行压缩 | + +以下是常用hitrace命令示例,供开发者参考: + +- 查询支持的label。 + + ``` + + hitrace -l + + ``` + + 或者 + + ``` + + hitrace --list_categories + + ``` + +- 设置4M缓存,抓取10秒,抓取label为ability的trace信息。 + + ``` + + hitrace -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace + + ``` + +- 设置trace的输出时钟为mono。 + + ``` + + hitrace --trace_clock mono -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace + + ``` + +- 抓取trace后进行压缩。 + + ``` + + hitrace -z -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace + + ``` + + + +# 常见问题 + +### hitrace抓数据不全或者没抓到数据 + +#### 现象描述 + +执行hitrace命令抓数据不全或者没抓到数据。 + +#### 根因分析 + +参数-t 时间设置过小或者-b缓冲区buffer设置过小导致数据丢失。 + +#### 解决方法 + +可设置-t 60,-b 204800扩大抓trace时间和缓冲区buffer解决。 + + + +# 参考 + +更多关于HiTraceMeter的详细内容请参考:[轻量级的分布式调用链跟踪](https://gitee.com/openharmony/hiviewdfx_hitrace) 。 + + diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-overview.md b/zh-cn/device-dev/subsystems/subsys-dfx-overview.md index f1c06a3c423a210fc491f7fe9c994ff242146cc9..9a5bff06a43d0d4de373c4ae3396eb33f98bf165 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-overview.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-overview.md @@ -7,16 +7,18 @@ 提供以下功能: -- HiLog流水日志,轻量系统类设备(参考内存≥128KiB)、小型系统类设备(参考内存≥1MiB)、标准系统类设备(参考内存≥128MB)适用。 +- HiLog流水日志,标准系统类设备(参考内存≥128MB)适用。 + +- HiLog_Lite轻量化流水日志,轻量系统类设备(参考内存≥128KiB)、小型系统类设备(参考内存≥1MiB)适用。 - HiTraceChain分布式跟踪,标准系统类设备(参考内存≥128MiB)适用。 +- HiTraceMeter性能跟踪,标准系统类设备(参考内存≥128MiB)适用。 + - HiCollie卡死故障检测,标准系统类设备(参考内存≥128MiB)适用。 - HiSysEvent系统事件埋点,标准系统类设备(参考内存≥128MiB)适用。 -- HiChecker缺陷扫描,标准系统类设备(参考内存≥128MB)适用。 - - HiDumper信息导出,标准系统类设备(参考内存≥128MB)适用。 - Faultlogger崩溃故障检测,标准系统类设备(参考内存≥128MB)适用。 diff --git a/zh-cn/device-dev/subsystems/subsys-power-brightness-customization.md b/zh-cn/device-dev/subsystems/subsys-power-brightness-customization.md new file mode 100644 index 0000000000000000000000000000000000000000..2bc3a430672cab658d556d5a5c1425c66cf6cd07 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-power-brightness-customization.md @@ -0,0 +1,191 @@ +# 系统亮度范围定制开发指导 + +## 概述 + +### 简介 + +OpenHarmony默认的亮度范围为0 ~ 255(0代表最小亮度,255代表最大亮度),是系统和所有应用窗口的亮度调节范围。部分显示设备受到其硬件约束,亮度调节范围无法达到0 ~ 255,即无法达到默认的亮度调节范围。为此OpenHarmony提供了系统亮度范围定制方式,在与不同显示设备适配时,产品定制开发者可根据显示设备自身硬件条件灵活调整系统亮度范围。 + +### 基本概念 + +系统亮度: +OpenHarmony系统全局的亮度,调节后会使所有应用窗口亮度范围更改为定制的系统亮度范围。 + +窗口亮度: +某个应用窗口的亮度,调节后只影响此窗口,窗口退出后,恢复为系统亮度。当设置窗口亮度后,此窗口的亮度不受系统亮度的影响。 + +### 约束与限制 + +[OpenHarmony系统参数](./subsys-boot-init-sysparam.md)为各系统服务提供简单易用的键值对访问接口,使得各个系统服务可以通过各自的系统参数来进行业务功能的配置。系统亮度范围的定制基于此特性实现。 + +## 开发指导 + +### 搭建环境 + +设备要求: + +标准系统开发板,如DAYU200/Hi3516DV300开源套件。 + +环境要求: + +Linux调测环境,相关要求和配置可参考《[快速入门](../quick-start/Readme-CN.md)》。 + +### 开发步骤 + +1. 参考[默认亮度范围配置文件夹](https://gitee.com/openharmony/powermgr_display_manager/tree/master/service/etc)创建目标文件夹,并安装到相应目录,文件格式如下: + + ```text + etc + ├── BUILD.gn + ├── display.para + ├── display.para.dac + ``` + +2. 参考[默认亮度范围配置文件夹中的display.para](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/display.para)编写定制的display.para。包含定制后的亮度阈值,以max=150,default=75,min=50为例: + + ```shell + # Brightness limits is 0-255. + const.display.brightness.min=50 + const.display.brightness.default=75 + const.display.brightness.max=150 + ``` + +3. 参考[默认亮度范围配置文件夹中的display.para.dac](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/display.para.dac)编写display.para.dac数据访问控制文件,保证有权限解析定制后的配置: + + ```shell + const.display.brightness.="foundation:foundation:444" + ``` + +4. 参考[默认亮度范围配置文件夹中的BUILD.gn](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/BUILD.gn)编写BUILD.gn文件,将display.para和display.para.dac打包到/vendor/etc/param目录下,例如: + + ```shell + import("//base/powermgr/display_manager/displaymgr.gni") + import("//build/ohos.gni") + + ## Install display.para to /vendor/etc/param/display.para + ohos_prebuilt_etc("display.para") { + source = "display.para" + relative_install_dir = "param" + install_images = [ chipset_base_dir ] + part_name = "${displaymgr_part_name}" + subsystem_name = "powermgr" + } + + ohos_prebuilt_etc("display.para.dac") { + source = "display.para.dac" + relative_install_dir = "param" + install_images = [ chipset_base_dir ] + part_name = "${displaymgr_part_name}" + subsystem_name = "powermgr" + } + + group("param_files") { + deps = [ + ":display.para", + ":display.para.dac", + ] + } + ``` + +5. 参考[默认亮度范围配置bundle.json](https://gitee.com/openharmony/powermgr_display_manager/blob/master/bundle.json)编写bundle.json文件,使BUILD.gn文件进行编译,例如: + + ```shell + "service_group": [ "//base/powermgr/display_manager/service/etc:param_files" ] + ``` + “//base/powermgr/display_manager/service”为文件夹路径,“etc”为创建的文件夹名字。 + +6. 参考《[快速入门](../quick-start/Readme-CN.md)》编译定制版本,以编译DAYU200为例,编译命令如下: + + ```shell + ./build.sh --product-name rk3568 --ccache + ``` + +7. 将定制版本烧录到DAYU200开发板中。 + +### 调测验证 + +1. 开机后,先进入shell命令行: + + ```shell + hdc shell + ``` + +2. 执行下列命令,观察console输出。 + + ```shell + hidumper -s 3308 -a -a + ``` + +3. console输出的是定制后的系统亮度阈值,如: + + 定制系统亮度阈值之前,默认为: + + ```shell + ----------------------------------DisplayPowerManagerService--------------------------------- + DISPLAY POWER MANAGER DUMP: + Display Id=0 State=2 Discount=1.000000 Brightness=102 + DeviceBrightness=102 + Support Ambient Light: FALSE + Auto Adjust Brightness: OFF + Brightness Limits: Max=255 Min=5 Default=102 + + ``` + + 本节以Max=150 Min=50 Default=75为例,更改之后: + + ```shell + # cd vendor/etc/param + # ls + display.para thermal.para usb.para.dac + display.para.dac thermal.para.dac + # cat display.para + # Copyright (C) 2022 Huawei 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. + + # Brightness limits is 0-255. + const.display.brightness.min=50 + const.display.brightness.default=75 + const.display.brightness.max=150# + # + # cd + # hidumper -s 3308 -a -a + + -------------------------------[ability]------------------------------- + + + ----------------------------------DisplayPowerManagerService--------------------------------- + DISPLAY POWER MANAGER DUMP: + Display Id=0 State=0 Discount=1.000000 Brightness=75 + DeviceBrightness=75 + Support Ambient Light: FALSE + Auto Adjust Brightness: OFF + Brightness Limits: Max=150 Min=50 Default=75 + + ``` + +4. 系统全局的亮度阈值统一为定制后的,如设置中的亮度调节。 + +## 参考 + +开发过程中可参考的配置文件路径:[系统默认亮度范围配置源码路径](https://gitee.com/openharmony/powermgr_display_manager/tree/master/service/etc) + +默认配置: + +```shell +# Brightness limits is 0-255. +const.display.brightness.min=5 +const.display.brightness.default=102 +const.display.brightness.max=255 +``` + +打包路径:/system/etc/param \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md b/zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md index 461e3f1dcd4036741d1bf5721c86789c0098262f..7dfe5ae62c8564df7a0cd77c9e4bf4ad23bc1b24 100644 --- a/zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md +++ b/zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @@ -207,6 +207,9 @@ Usage: hiperf record [options] ## report 命令 + +### 参数说明 + 此命令主要用于展示record中抓取的采样数据 @@ -230,7 +233,7 @@ Usage: hiperf report [option] | -o <_filename_> | 指定输出的报告文件名。 | -## 使用示例 +### 使用示例 - 输出采样数据的报告,默认读取perf.data文件 diff --git a/zh-cn/device-dev/subsystems/subsys-usbservice-demo.md b/zh-cn/device-dev/subsystems/subsys-usbservice-demo.md deleted file mode 100644 index ad6e84ec1ce098166779ea978ed39345448eda09..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-usbservice-demo.md +++ /dev/null @@ -1,187 +0,0 @@ -# USB服务子系统使用实例 - - -```cpp -#include -#include -#include -#include -#include -#include -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" -#include "iremote_object.h" -#include "iservice_registry.h" -#include "iusb_srv.h" -#include "string_ex.h" -#include "system_ability_definition.h" -#include "usb_common.h" -#include "usb_device.h" -#include "usb_errors.h" -#include "usb_request.h" -#include "usb_server_proxy.h" -#include "usb_srv_client.h" - -const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f)); -const int32_t REQUESTCMD = 6; -const int32_t VALUE = (2 << 8) + 0; -const int32_t TIMEOUT = 5000; -const int32_t ITFCLASS = 10; -const int32_t PRAMATYPE = 2; -const int32_t BUFFERLENGTH = 21; - -void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg) -{ - if ((tep.GetType() == PRAMATYPE)) { - if (tep.GetDirection() == 0) { - outEp = tep; - outEpFlg = true; - } - } -} - -bool SelectEndpoint(OHOS::USB::USBConfig config, - std::vector interfaces, - OHOS::USB::UsbInterface &interface, - OHOS::USB::USBEndpoint &outEp, - bool &outEpFlg) -{ - for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) { - OHOS::USB::UsbInterface tif = interfaces[i]; - std::vector mEndpoints = tif.GetEndpoints(); - for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) { - OHOS::USB::USBEndpoint tep = mEndpoints[j]; - if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) { - GetType(tep, outEp, outEpFlg); - } - } - if (outEpFlg) { - interface = interfaces[i]; - return true; - } - std::cout << std::endl; - } - return false; -} - -int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip) -{ - int ret = Instran.RequestRight(device.GetName()); - std::cout << "device RequestRight ret = " << ret << std::endl; - if (0 != ret) { - std::cout << "device RequestRight failed = " << ret << std::endl; - } - ret = Instran.OpenDevice(device, pip); - return ret; -} - -int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip) -{ - std::cout << "usb_device_test : << Control Transfer >> " << std::endl; - std::vector vData; - const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT}; - int ret = Instran.ControlTransfer(pip, tctrl, vData); - if (ret != 0) { - std::cout << "control message read failed width ret = " << ret << std::endl; - } else { - } - std::cout << "control message read success" << std::endl; - - return ret; -} - -int ClaimTest(OHOS::USB::UsbSrvClient &Instran, - OHOS::USB::USBDevicePipe &pip, - OHOS::USB::UsbInterface &interface, - bool interfaceFlg) -{ - if (interfaceFlg) { - std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl; - int ret = Instran.ClaimInterface(pip, interface, true); - if (ret != 0) { - std::cout << "ClaimInterface failed width ret = " << ret << std::endl; - } else { - std::cout << "ClaimInterface success" << std::endl; - } - } - return 0; -} - -int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran, - OHOS::USB::USBDevicePipe &pip, - OHOS::USB::USBEndpoint &outEp, - bool interfaceFlg, - bool outEpFlg) -{ - if (interfaceFlg) { - std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl; - if (outEpFlg) { - uint8_t buffer[50] = "hello world 123456789"; - std::vector vData(buffer, buffer + BUFFERLENGTH); - int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT); - if (ret != 0) { - std::cout << "Bulk transfer write failed width ret = " << ret << std::endl; - } else { - std::cout << "Bulk transfer write success" << std::endl; - } - return ret; - } - } - return 0; -} - -int main(int argc, char **argv) -{ - std::cout << "usb_device_test " << std::endl; - static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance(); - // GetDevices - std::vector deviceList; - int32_t ret = Instran.GetDevices(deviceList); - if (ret != 0) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - if (deviceList.empty()) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - - OHOS::USB::UsbDevice device = deviceList[0]; - std::vector configs = device.GetConfigs(); - OHOS::USB::USBConfig config = configs[0]; - std::vector interfaces = config.GetInterfaces(); - OHOS::USB::UsbInterface interface; - OHOS::USB::USBEndpoint outEp; - bool interfaceFlg = false; - bool outEpFlg = false; - interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg); - - // OpenDevice - std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl; - OHOS::USB::USBDevicePipe pip; - ret = OpenDeviceTest(Instran, device, pip); - if (ret != 0) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - - // ControlTransfer - CtrTransferTest(Instran, pip); - - // ClaimInterface - ClaimTest(Instran, pip, interface, interfaceFlg); - - // BulkTransferWrite - BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg); - - // CloseDevice - std::cout << "usb_device_test : << Close Device >> " << std::endl; - ret = Instran.Close(pip); - if (ret == 0) { - std::cout << "Close device failed width ret = " << ret << std::endl; - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } else { - std::cout << "Close Device success" << std::endl; - } - return 0; -} -``` - - diff --git a/zh-cn/device-dev/subsystems/subsys-usbservice-guide.md b/zh-cn/device-dev/subsystems/subsys-usbservice-guide.md deleted file mode 100644 index ea46f8f7e445897feb58684f702ef578e466a8f8..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-usbservice-guide.md +++ /dev/null @@ -1,51 +0,0 @@ -# USB服务子系统使用指导 - - -下面使用步骤以bulktransfer为例。 - -使用步骤 - -1. 获取usb service实例 - - ```cpp - static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance(); - ``` - -2. 获取usb设备列表 - - ```cpp - std::vector deviceList; - int32_t ret = g_usbClient.GetDevices(deviceList); - ``` - -3. 申请设备权限 - - ```cpp - int32_t ret = g_usbClient.RequestRight(device.GetName()); - ``` - -4. 打开设备 - - ```cpp - USBDevicePipe pip; - int32_t et = g_usbClient.OpenDevice(device, pip); - ``` - -5. 配置设备接口 - - ```cpp - ret = g_usbClient.ClaimInterface(pip, interface, true); //interface为deviceList中device的interface。 - ``` - -6. 数据传输 - - ```cpp - srvClient.BulkTransfer(pipe, endpoint, vdata, timeout); - ``` - pipe为打开设备后的数据传输通道,endpoint为device中数据传输的端点,vdata是需要传输或读取的二进制数据块,timeout为传输超时时长。 - -7. 关闭设备 - - ```cpp - ret = g_usbClient.Close(pip); - ``` diff --git a/zh-cn/device-dev/subsystems/subsys-usbservice-overview.md b/zh-cn/device-dev/subsystems/subsys-usbservice-overview.md deleted file mode 100644 index d3bf8b07e67ce76f23a2b66a6add3887cbe522cf..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-usbservice-overview.md +++ /dev/null @@ -1,338 +0,0 @@ -# USB服务 - -## 概述 - -### 功能简介 - -USB设备分为Host设备(主机设备)和Device设备(从设备)。用户可通过Port Service来根据实际业务把运行OpenHarmony的设备切换为Host设备或者Device设备。目前在Host模式下,支持获取USB设备列表,USB设备权限管理,控制传输、批量传输的同异步数据传输等,在Device模式下,支持HDC(调试)、ACM(串口)、ECM(网口)等功能的切换。 - -### 基本概念 - -- USB服务 - - USB服务是应用访问底层的一种设备抽象概念。开发者根据提供的USB API,可以获取设备列表、控制设备访问权限、以及与连接的设备进行数据传输、控制命令传输等。 - -- USB API - - 基于USB Service服务,使用NAPI技术,向上提供JS接口。提供USB的基础API,主要包含查询USB设备的列表、设备插拔通知、USB HOST/DEVICE 功能切换、批量数据传输、控制命令传输、USB设备打开的权限控制及USB device模式下的function功能切换等。 - -- USB Service - - 使用C++代码实现,包含Host、Device、Port、Right四个模块。基于HDI接口,主要实现USB设备列表管理、Function 管理、Port管理、USB设备权限管理等功能。主要实现HAL层数据接收、解析、分发,前后台的策略管控,对该设备USB的管理,USB权限管控等。 - -- USB HAL - - 使用C代码实现,基于Host DDK(Driver Develop Kit)和Device DDK,封装了对USB设备的基本操作,向上提供C++接口,同时通过HDF框架接收内核上报的信息。 - -### 运作机制 - -USB服务系统包含USB API、USB Service、USB HAL。 - - **图1** USB服务架构图 - ![zh-cn_image_0000001267088285](figures/zh-cn_image_0000001267088285.png) - -- USB API:提供USB的基础API,主要包含查询USB设备列表、批量数据传输、控制命令传输、权限控制等。 - -- USB Service:主要实现HAL层数据的接收、解析、分发,前后台的策略管控以及对设备的管理等。 - -- USB HAL层:提供给用户态可直接调用的驱动能力接口。 - -## 使用指导 - -### 场景介绍 - -Host模式下,可以获取到已经连接的设备列表,并根据需要打开和关闭设备、控制设备权限、进行数据传输等。 - -### 接口说明 - - **表1** Host部分 - -| 接口名称 | 功能描述 | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | 打开USB设备,建立连接 | -| bool HasRight(std::string deviceName); | 判断是否有权访问设备 | -| int32_t RequestRight(std::string deviceName); | 请求给定软件包的临时权限以访问设备 | -| int32_t GetDevices(std::vector &deviceList); | 获取USB设备列表 | -| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | 打开接口,并申明独占接口,必须在数据传输前执行 | -| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | 关闭接口,释放接口的占用,在停止数据传输后执行 | -| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector &vdata, int32_t timeout); | 在给定端点上执行批量数据传输, 返回读取或发送的数据长度,通过端点方向确定读取或发送数据 | -| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector &vdata); | 对此设备执行端点零的控制事务,传输方向由请求类型决定 | -| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | 设置设备当前使用的配置,通过配置值进行指定 | -| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | 设置指定接口的备选设置,用于在具有相同ID但不同备用设置的两个接口之间进行选择 | -| int32_t GetRawDescriptors(std::vector &vdata); | 获取原始的USB描述符 | -| int32_t GetFileDescriptor(); | 获取文件描述符 | -| bool Close(const USBDevicePipe &pip); | 关闭设备,释放与设备相关的所有系统资源 | -| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | 获取异步传输结果 | -| int32_t RequestInitialize(UsbRequest &request); | 初始化异步数据传输request | -| int32_t RequestFree(UsbRequest &request); | 释放异步数据传输request | -| int32_t RequestAbort(UsbRequest &request); | 取消待处理的数据请求 | -| int32_t RequestQueue(UsbRequest &request); | 将指定的端点进行异步数据发送或者接收请求,数据传输方向由端点方向决定 | -| int32_t RegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint, const sptr &cb); | 注册批量传输异步回调函数 | -| int32_t UnRegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint); | 注销批量传输异步回调函 | -| int32_t BulkRead(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr &ashmem); | 批量传输异步读数据 | -| int32_t BulkWrite(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr &ashmem); | 批量传输异步写 | -| int32_t BulkCancel(USBDevicePipe &pip, const USBEndpoint &endpoint); | 批量传输异步取消接口,用于取消当前接口的异步批量读写操作 | - - **表2** Device部分 - -| 接口名称 | 功能描述 | -| -------------------------------------------------- | ------------------------------------------------------ | -| int32_t GetCurrentFunctions(int32_t &funcs); | 获取设备模式下的当前USB功能列表的数字组合掩码 | -| int32_t SetCurrentFunctions(int32_t funcs); | 在设备模式下设置当前的USB功能列表 | -| int32_t UsbFunctionsFromString(std::string funcs); | 将给定的功能列表描述字符串转换为功能列表的数字组合掩码 | -| std::string UsbFunctionsToString(int32_t funcs); | 将给定的功能列表的数字组合掩码转换为功能列表描述字符串 | - - **表3** Port部分 - -| 接口名称 | 功能描述 | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | 获取指定的端口支持的模式列表的组合掩码 | -| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | 设置指定的端口支持的角色模式,包含充电角色、数据传输角色 | -| int32_t GetPorts(std::vector &usbPorts); | 获取物理USB端口描述信息列表 | - -### USB服务子系统使用步骤 - -以bulktransfer为例。 - -1. 获取usb service实例。 - - ```cpp - static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance(); - ``` - -2. 获取usb设备列表。 - - ```cpp - std::vector deviceList; - int32_t ret = g_usbClient.GetDevices(deviceList); - ``` - -3. 申请设备权限。 - - ```cpp - int32_t ret = g_usbClient.RequestRight(device.GetName()); - ``` - -4. 打开设备。 - - ```cpp - USBDevicePipe pip; - int32_t et = g_usbClient.OpenDevice(device, pip); - ``` - -5. 配置设备接口。 - - ```cpp - //interface为deviceList中device的interface。 - ret = g_usbClient.ClaimInterface(pip, interface, true); - ``` - -6. 数据传输。 - - ```cpp - // pipe为打开设备后的数据传输通道,endpoint为device中数据传输的端点,vdata是需要传输或读取的二进制数据块,timeout为传输超时时长。 - srvClient.BulkTransfer(pipe, endpoint, vdata, timeout); - ``` - -7. 关闭设备。 - - ```cpp - ret = g_usbClient.Close(pip); - ``` - -### USB服务子系统使用实例 - -```cpp -#include -#include -#include -#include -#include -#include -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" -#include "iremote_object.h" -#include "iservice_registry.h" -#include "iusb_srv.h" -#include "string_ex.h" -#include "system_ability_definition.h" -#include "usb_common.h" -#include "usb_device.h" -#include "usb_errors.h" -#include "usb_request.h" -#include "usb_server_proxy.h" -#include "usb_srv_client.h" - -const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f)); -const int32_t REQUESTCMD = 6; -const int32_t VALUE = (2 << 8) + 0; -const int32_t TIMEOUT = 5000; -const int32_t ITFCLASS = 10; -const int32_t PRAMATYPE = 2; -const int32_t BUFFERLENGTH = 21; - -void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg) -{ - if ((tep.GetType() == PRAMATYPE)) { - if (tep.GetDirection() == 0) { - outEp = tep; - outEpFlg = true; - } - } -} - -bool SelectEndpoint(OHOS::USB::USBConfig config, - std::vector interfaces, - OHOS::USB::UsbInterface &interface, - OHOS::USB::USBEndpoint &outEp, - bool &outEpFlg) -{ - for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) { - OHOS::USB::UsbInterface tif = interfaces[i]; - std::vector mEndpoints = tif.GetEndpoints(); - for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) { - OHOS::USB::USBEndpoint tep = mEndpoints[j]; - if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) { - GetType(tep, outEp, outEpFlg); - } - } - if (outEpFlg) { - interface = interfaces[i]; - return true; - } - std::cout << std::endl; - } - return false; -} - -int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip) -{ - int ret = Instran.RequestRight(device.GetName()); - std::cout << "device RequestRight ret = " << ret << std::endl; - if (0 != ret) { - std::cout << "device RequestRight failed = " << ret << std::endl; - } - ret = Instran.OpenDevice(device, pip); - return ret; -} - -int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip) -{ - std::cout << "usb_device_test : << Control Transfer >> " << std::endl; - std::vector vData; - const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT}; - int ret = Instran.ControlTransfer(pip, tctrl, vData); - if (ret != 0) { - std::cout << "control message read failed width ret = " << ret << std::endl; - } else { - } - std::cout << "control message read success" << std::endl; - - return ret; -} - -int ClaimTest(OHOS::USB::UsbSrvClient &Instran, - OHOS::USB::USBDevicePipe &pip, - OHOS::USB::UsbInterface &interface, - bool interfaceFlg) -{ - if (interfaceFlg) { - std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl; - int ret = Instran.ClaimInterface(pip, interface, true); - if (ret != 0) { - std::cout << "ClaimInterface failed width ret = " << ret << std::endl; - } else { - std::cout << "ClaimInterface success" << std::endl; - } - } - return 0; -} - -int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran, - OHOS::USB::USBDevicePipe &pip, - OHOS::USB::USBEndpoint &outEp, - bool interfaceFlg, - bool outEpFlg) -{ - if (interfaceFlg) { - std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl; - if (outEpFlg) { - uint8_t buffer[50] = "hello world 123456789"; - std::vector vData(buffer, buffer + BUFFERLENGTH); - int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT); - if (ret != 0) { - std::cout << "Bulk transfer write failed width ret = " << ret << std::endl; - } else { - std::cout << "Bulk transfer write success" << std::endl; - } - return ret; - } - } - return 0; -} - -int main(int argc, char **argv) -{ - std::cout << "usb_device_test " << std::endl; - static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance(); - // GetDevices - std::vector deviceList; - int32_t ret = Instran.GetDevices(deviceList); - if (ret != 0) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - if (deviceList.empty()) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - - OHOS::USB::UsbDevice device = deviceList[0]; - std::vector configs = device.GetConfigs(); - OHOS::USB::USBConfig config = configs[0]; - std::vector interfaces = config.GetInterfaces(); - OHOS::USB::UsbInterface interface; - OHOS::USB::USBEndpoint outEp; - bool interfaceFlg = false; - bool outEpFlg = false; - interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg); - - // OpenDevice - std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl; - OHOS::USB::USBDevicePipe pip; - ret = OpenDeviceTest(Instran, device, pip); - if (ret != 0) { - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } - - // ControlTransfer - CtrTransferTest(Instran, pip); - - // ClaimInterface - ClaimTest(Instran, pip, interface, interfaceFlg); - - // BulkTransferWrite - BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg); - - // CloseDevice - std::cout << "usb_device_test : << Close Device >> " << std::endl; - ret = Instran.Close(pip); - if (ret == 0) { - std::cout << "Close device failed width ret = " << ret << std::endl; - return OHOS::USB::UEC_SERVICE_INVALID_VALUE; - } else { - std::cout << "Close Device success" << std::endl; - } - return 0; -} -``` - -### 参考手册 - -[驱动子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E9%A9%B1%E5%8A%A8%E5%AD%90%E7%B3%BB%E7%BB%9F.md) - -[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md) - -[drivers\_framework](https://gitee.com/openharmony/drivers_framework/blob/master/README_zh.md) - -[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README_zh.md) - -[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README_zh.md) \ No newline at end of file diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 221a960eb6e41f361cddaf2663aefb7afdb61026..828da2a577fbd9258ae5b60131e58df35fab64ef 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -429,10 +429,6 @@ - [Sensor服务概述](subsystems/subsys-sensor-overview.md) - [Sensor服务使用指导](subsystems/subsys-sensor-guide.md) - [Sensor服务使用实例](subsystems/subsys-sensor-demo.md) - - USB服务 - - [USB服务概述](subsystems/subsys-usbservice-overview.md) - - [USB服务使用指导](subsystems/subsys-usbservice-guide.md) - - [USB服务使用实例](subsystems/subsys-usbservice-demo.md) - 用户程序框架 - [概述](subsystems/subsys-application-framework-overview.md) - [搭建环境](subsystems/subsys-application-framework-envbuild.md) diff --git "a/zh-cn/readme/XTS\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/XTS\345\255\220\347\263\273\347\273\237.md" index 5823bbe96cf62a4e1fb6f9b5fec6f30d0055a425..35ef584fb9476f59d9a445e60e40de231296f29e 100755 --- "a/zh-cn/readme/XTS\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/XTS\345\255\220\347\263\273\347\273\237.md" @@ -347,7 +347,7 @@ OpenHarmony支持如下几种系统类型: 随版本编译,debug版本编译时会同步编译acts测试套件 - >![](public_sys-resources/icon-note.gif) **说明:** + >**说明:** >acts测试套件编译中间件为静态库,最终链接到版本镜像中 。 @@ -480,7 +480,7 @@ OpenHarmony支持如下几种系统类型: 随版本编译,debug版本编译时会同步编译acts测试套件 - >![](public_sys-resources/icon-note.gif) **说明:** + >**说明:** >小型系统acts独立编译成可执行文件(bin格式), 在编译产物的suites\\acts目录下归档。 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..3d3cf5c436387fa04e1bfc085d7bf52e7507095b --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md @@ -0,0 +1,122 @@ +# OpenHarmony 3.0.8 LTS + + +## 版本概述 + +此版本为OpenHarmony-3.0-LTS分支上的维护版本,基于OpenHarmony-v3.0.7-LTS版本修复一些安全问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.0.8 LTS | NA | +| HUAWEI DevEco Studio(可选) | 3.0 Beta3 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.0.8-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.8-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + + **表2** 获取源码路径 + +| **LTS版本源码** | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.0.8 | [站点](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/code-v3.0.8-LTS.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/code-v3.0.8-LTS.tar.gz.sha256) | +| 标准系统Hi3516解决方案(二进制) | 3.0.8 | [站点](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/standard.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/standard.tar.gz.sha256) | +| 轻量系统Hi3861解决方案(二进制) | 3.0.8 | [站点](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_pegasus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-LiteOS(二进制) | 3.0.8 | [站点](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-Linux(二进制) | 3.0.8 | [站点](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/harmonyos/os/3.0.8/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编号 | 描述 | 合入链接 | +| -------- | -------- | -------- | +| I5UHRW | 修复组件Kernel_linux_5.10上的CVE-2022-41218、CVE-2022-3424、CVE-2022-42328、CVE-2022-3643、CVE-2022-47946安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/647) | +| I648XK | 修复组件Kernel_linux_5.10上的CVE-2022-3169安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/561) | +| I5QBIA | 修复组件Kernel_linux_5.10上的CVE-2022-1184安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/475) | +| I62G8K | 修复组件Kernel_linux_5.10上的CVE-2022-42895、CVE-2022-42896安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/545) | +| I63VI6 | 修复组件Kernel_linux_5.10上的CVE-2022-41858安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/570) | +| I63VID | 修复组件Kernel_linux_5.10上的CVE-2022-45934、CVE-2022-4129、CVE-2022-4378、CVE-2022-3108、CVE-2022-47518、CVE-2022-47521、CVE-2022-47519、CVE-2022-47520安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/587) | +| I65INV | 修复组件Kernel_linux_5.10上的CVE-2022-4139安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/568) | +| I66Y94 | 修复组件Kernel_linux_5.10上的CVE-2022-3105、CVE-2022-3104、CVE-2022-3115、CVE-2022-3113、CVE-2022-3112安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/580) | +| I66Y9Y | 修复组件Kernel_linux_5.10上的CVE-2022-3106安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/593) | +| I66YAD | 修复组件Kernel_linux_5.10上的CVE-2022-3107安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/591) | +| I6A4HN | 修复组件Kernel_linux_5.10上的CVE-2022-20568安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/630) | +| I6A4IZ | 修复组件Kernel_linux_5.10上的CVE-2023-20928安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/654) | +| I6B0AN | 修复组件Kernel_linux_5.10上的CVE-2022-4696安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/664) | +| I6B0B4 | 修复组件Kernel_linux_5.10上的CVE-2023-23559、CVE-2023-0179、CVE-2023-23454、CVE-2023-23455安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/662) | +| I65R5Q | 修复组件third_party_python上的CVE-2022-45061安全漏洞 | [PR](https://gitee.com/openharmony/third_party_python/pulls/40) | +| I6494T | 修复组件third_party_libxml2上的CVE-2022-40303、CVE-2022-40304安全漏洞 | [PR](https://gitee.com/openharmony/third_party_libxml2/pulls/32) | +| I5ZYY3 | 修复组件third_party_pixman上的CVE-2022-44638安全漏洞 | [PR](https://gitee.com/openharmony/third_party_pixman/pulls/12) | +| I5UHVA | 修复组件third_party_u-boot上的CVE-2022-2347安全漏洞 | [PR](https://gitee.com/openharmony/third_party_u-boot/pulls/63) | + + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-bundlemanager.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..8cb911d0fe15bf51e1a612d63010d50849b2ffc5 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-bundlemanager.md @@ -0,0 +1,60 @@ +# 包管理子系统ChangeLog + +## cl.bundlemanager.1 app.json配置文件删除atomicService标签 +删除配置文件app.json中atomicService标签 + +**变更影响**
+删除配置文件app.json中atomicService标签,IDE中不再支持配置该标签,使用该标签会导致IDE编译报错 + +**适配指导**
+删除atomicService标签 + +## cl.bundlemanager.2 app.json配置文件新增bundleType标签 +配置文件app.json中新增bundleType标签 + +**变更影响**
+现存的元服务([installationFree](../../../application-dev/quick-start/module-configuration-file.md)为true),必须在app.json中指定bundleType为atomicService,否则打包失败。 + +**适配指导**
+新增[bundleType](../../../application-dev/quick-start/app-configuration-file.md)标签。该标签为可缺省(缺省值为app)。该标签需要和module.json中[installationFree](../../../application-dev/quick-start/module-configuration-file.md)字段保持一一对应,其相应规则为: +- 当bundleType为app时,installationFree必须为false。 +- 当bundleType为atomicService时,installationFree必须为true。 + +## cl.bundlemanager.3 包管理ApplicationInfo结构体中删除split字段。 + +包管理[ApplicationInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ApplicationInfo.d.ts)结构体中删除split字段。 + +**变更影响**
+使用之前已发布的API 9各beta版本且使用到了split的,会编译失败。 + +**关键的接口/组件变更**
+包管理[ApplicationInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ApplicationInfo.d.ts)结构体中删除split字段。 + +**适配指导**
+删除ApplicationInfo结构体中的split字段。目前元服务中stage模型强制分包,不支持不分包。 + +## cl.bundlemanager.4 包管理HapModuleInfo结构体中删除atomicServiceModuleType字段。 + +包管理[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中删除atomicServiceModuleType字段。 + +**变更影响**
+使用之前已发布的API 9各beta版本且使用到了atomicServiceModuleType的,会编译失败。 + +**关键的接口/组件变更**
+包管理[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中删除atomicServiceModuleType字段。 + +**适配指导**
+删除[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中的atomicServiceModuleType字段。判断atomicServiceModuleType字段的部分,用[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中的moduleType代替。 + +## cl.bundlemanager.5 包管理删除AtomicServiceModuleType枚举值。 + +包管理[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中删除atomicServiceModuleType字段。 + +**变更影响**
+使用之前已发布的API 9各beta版本且使用到了atomicServiceModuleType的,会编译失败。 + +**关键的接口/组件变更**
+包管理[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中删除atomicServiceModuleType字段。 + +**适配指导**
+删除[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中的atomicServiceModuleType字段。判断atomicServiceModuleType字段的部分,用[HapModuleInfo](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)结构体中的moduleType代替。 \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-screenlock.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-screenlock.md new file mode 100644 index 0000000000000000000000000000000000000000..8e5a2fab3671eb32db8accb72d764a1194f26ff1 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-screenlock.md @@ -0,0 +1,155 @@ +# 主题框架子系统-锁屏管理服务ChangeLog + + +## cl.screenlock.1 isLocked、unlock接口使用权限变更 +从API9开始,变更为systemapi,停止对三方应用开放。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +基于此前版本开发的应用,需适配变更的js接口,变更前的接口已经不能正常使用了,否则会影响原有功能。 + +- 涉及接口 + +```js + function isLocked(): boolean; + function unlock(callback: AsyncCallback): void; + function unlock():Promise; +``` + +- 变更前: + +```js + * Checks whether the screen is currently locked. + * + * @returns Returns {@code true} if the screen is currently locked; returns {@code false} otherwise. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function isLocked(): boolean; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function unlock(callback: AsyncCallback): void; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function unlock():Promise; +``` + +- 变更后: + +```js + * Checks whether the screen is currently locked. + * + * @returns Returns {@code true} if the screen is currently locked; returns {@code false} otherwise. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function isLocked(): boolean; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function unlock(callback: AsyncCallback): void; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function unlock():Promise; +``` + + +**适配指导** + +该接口变更为系统应用后,三方应用已无法使用。 +系统应用可正常使用。 +示例代码如下: + +```js + try { + let ret = screenLock.isLocked(); + console.error(`Obtain whether the screen is locked successfully , ret is: ${ret}`); + } catch (error) { + console.error(`Failed to obtain whether the screen is locked, error is : ${error.code}, ${error.message}`); + } +``` + +```js + screenlock.unlock((err, data) => { + if (err) { + console.error(`Failed to unlock the screen, because: ${err.message}`); + return; + } + console.info(`unlock the screen successfully. result: ${data}`); + }); +``` + +```js + screenlock.unlock().then((data) => { + console.info(`unlock the screen successfully. result: ${data}`); + }).catch((err) => { + console.error(`Failed to unlock the screen, because: ${err.message}`); + }); +``` + + +## cl.screenlock.2 isSecure接口废弃变更 +从API9开始,废弃此接口。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +该接口删除无法再使用,请使用进行更新使用,否则会影响原有功能。 + +- 涉及接口 + +```js + function isSecure(): boolean; +``` + +- 变更前: + +```js + function isSecure(): boolean; +``` + +- 变更后:删除接口,停止对外开放。 + + +**适配指导** + +该接口删除后无法再使用,请适配更新。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-wallpaper.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-wallpaper.md new file mode 100644 index 0000000000000000000000000000000000000000..d3b6dfdf0a1426295d9ebf5203962c3e3b3d09a6 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.12/changelog-wallpaper.md @@ -0,0 +1,292 @@ +# 主题框架子系统-壁纸管理服务ChangeLog + + +## cl.wallpaper.1 getColorsSync、getMinHeightSync、getMinWidthSync、restore、setImage接口使用权限变更 +从API9开始,变更为systemapi,停止对三方应用开放。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +基于此前版本开发的应用,需适配变更的js接口,变更前的接口已经不能正常使用了,否则会影响原有功能。 + +- 涉及接口 + +```js + function getColorsSync(wallpaperType: WallpaperType): Array; + function getMinHeightSync(): number; + function getMinWidthSync(): number; + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + function restore(wallpaperType: WallpaperType): Promise; + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + +- 变更前: + +```js + /** + * Obtains the wallpaper colors for the wallpaper of the specified type. Returns rgbaColor type of array callback function. + * @param wallpaperType Indicates the wallpaper type. + * @returns { Array } the Array returned by the function. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getColorsSync(wallpaperType: WallpaperType): Array; + + /** + * Obtains the minimum height of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getMinHeightSync(): number; + + /** + * Obtains the minimum width of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getMinWidthSync(): number; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function restore(wallpaperType: WallpaperType): Promise; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + +- 变更后: + +```js + /** + * Obtains the wallpaper colors for the wallpaper of the specified type. Returns rgbaColor type of array callback function. + * @param wallpaperType Indicates the wallpaper type. + * @returns { Array } the Array returned by the function. + * @throws {BusinessError} 401 - parameter error. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getColorsSync(wallpaperType: WallpaperType): Array; + + /** + * Obtains the minimum height of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getMinHeightSync(): number; + + /** + * Obtains the minimum width of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getMinWidthSync(): number; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function restore(wallpaperType: WallpaperType): Promise; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + + +**适配指导** + +该接口变更为系统应用后,三方应用已无法使用。 +系统应用可正常使用。 +示例代码如下: + +```js + try { + let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); + console.log(`success to getColorsSync: ${JSON.stringify(colors)}`); + } catch (error) { + console.error(`failed to getColorsSync because: ${JSON.stringify(error)}`); + } +``` + +```js + let minHeight = wallpaper.getMinHeightSync(); +``` + +```js + let minWidth = wallpaper.getMinWidthSync(); +``` + +```js + wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to restore.`); + }); +``` + +```js + wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to restore.`); + }).catch((error) => { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + }); +``` + +```js + // source类型为string + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); + }); +``` + +```js + // source类型为string + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); + }).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + }); +``` + + +## cl.wallpaper.2 getIdSync、getFileSync、isChangeAllowed、isUserChangeAllowed、on、off接口废弃变更 +从API9开始,废弃此接口。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +该接口删除无法再使用,请使用进行更新使用,否则会影响原有功能。 + +- 涉及接口 + +```js + function getIdSync(wallpaperType: WallpaperType): number; + function getFileSync(wallpaperType: WallpaperType): number; + function isChangeAllowed(): boolean; + function isUserChangeAllowed(): boolean; + function on(type: 'colorChange', callback: (colors: Array, wallpaperType: WallpaperType) => void): void; + function off(type: 'colorChange', callback?: (colors: Array, wallpaperType: WallpaperType) => void): void; +``` + +- 变更前: + +```js + function getIdSync(wallpaperType: WallpaperType): number; + function getFileSync(wallpaperType: WallpaperType): number; + function isChangeAllowed(): boolean; + function isUserChangeAllowed(): boolean; + function on(type: 'colorChange', callback: (colors: Array, wallpaperType: WallpaperType) => void): void; + function off(type: 'colorChange', callback?: (colors: Array, wallpaperType: WallpaperType) => void): void; +``` + +- 变更后:删除接口,停止对外开放。 + + +**适配指导** + +该接口删除后无法再使用,请适配更新。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md index 5740c1bc54aa92cc3e32843d28ad907d7ad39e21..39968eb10919ed8bf08043a50f47d79bc248e9e6 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md @@ -107,3 +107,160 @@ let appContext = context.getApplicationContext(); appContext.getRunningProcessInformation() ``` + + +## cl.ability.4 WantConstant.Flags接口变更 +WantConstant.Flags接口有多个无效Flag定义,删除掉无效的Flag。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_FORWARD_RESULT | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CONTINUATION | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_NOT_OHOS_COMPONENT | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_FORM_ENABLED | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_AUTH_PREFIX_URI_PERMISSION | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITYSLICE_MULTI_DEVICE | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_START_FOREGROUND_ABILITY | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_INSTALL_WITH_BACKGROUND_MODE | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_CLEAR_MISSION | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_NEW_MISSION | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_MISSION_TOP | 删除 | + + + +## cl.ability.5 WantConstant.Action接口变更 +WantConstant.Action接口有多个无效Action定义,删除掉无效的Action。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_APP_ACCOUNT_AUTH | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_MARKET_DOWNLOAD | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | ACTION_MARKET_CROWDTEST | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_SANDBOX | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_BUNDLE_NAME | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_MODULE_NAME | 删除 | +| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_ABILITY_NAME | 删除 | + + + +## cl.ability.6 Caller相关接口变更 +Caller相关接口使用RPC废弃的Sequenceable和MessageParcel对象,使用RPC在API9提供的Parcelable和MessageSequence对象替代。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| api/@ohos.app.ability.UIAbility.d.ts | CalleeCallback | (indata: rpc.MessageParcel): rpc.Sequenceable; | 变更,修改为 (indata: rpc.MessageSequence): rpc.Parcelable; | +| api/@ohos.app.ability.UIAbility.d.ts | Caller | call(method: string, data: rpc.Sequenceable): Promise; | 变更,修改为 call(method: string, data: rpc.Parcelable): Promise; | +| api/@ohos.app.ability.UIAbility.d.ts | Caller | callWithResult(method: string, data: rpc.Sequenceable): Promise; | 变更,修改为 callWithResult(method: string, data: rpc.Parcelable): Promise; | + +**适配指导** + +应用中调用Caller相关接口可参考下列代码 + +变更前代码: + +```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + let method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readSequenceable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } +``` + +变更后代码: + +```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + let method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readParcelable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } +``` + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.3/changelogs-useriam.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.3/changelogs-useriam.md new file mode 100644 index 0000000000000000000000000000000000000000..e781172a332f8bc19c89d43cfa72c29eb8df44d3 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.3/changelogs-useriam.md @@ -0,0 +1,39 @@ +# 用户IAM子系统Changelog + +## cl.useriam.1 API9 GetVesion接口删除 + +为优化用户IAM接口,从当前版本开始做如下变更: + +用户IAM删除GetVersion(API 9)接口。 + +**变更影响** + +对用户IAM GetVersion(API 9)接口的使用有影响,需删除对此接口的调用,否则会调用失败。 + +**关键接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ---------------------- | ------------------- | ------------------------- | ------------------------ | +| ohos.userIAM.userAuth | function | getVersion() : number | 删除 | + +**适配指导** + +需删除对用户IAM GetVersion(API 9)接口的调用。 + +## cl.useriam.2 API8 GetVesion接口返回值变更 + +为统一用户IAM GetVersion(API 8)接口的返回值。从当前版本开始做如下变更: + +用户IAM GetVersion(API 8)接口的返回值由0变更为1。 + +**变更影响** + +对用户IAM GetVersion(API 8)接口的使用有影响,如应用校验了此接口的返回值,修改后校验不通过。 + +**关键接口/组件变更** + +用户IAM GetVersion(API 8)接口的返回值由0变更为1。 + +**适配指导** + +此接口已废弃,需删除对用户IAM GetVersion(API 8)接口的使用。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-ability.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..ba5ef87f8bb33c7ffb56cba4e92e711f07248c79 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.2/changelogs-ability.md @@ -0,0 +1,64 @@ +# 元能力子系统ChangeLog + +## cl.ability.appRecovery新增saveAppState接口 + +新增接口saveAppState(context?: UIAbilityContext): boolean; + +**变更影响** + +基于OpenHarmony4.0.5.2及之后的SDK版本开发的应用,可以使用saveAppState接口传入指定Ability Context,实现主动保存指定的Ability状态。 + +**关键接口/组件变更** + +@ohos.app.ability.appRecovery.d.ts中新增saveAppState接口。 + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| -- | -- | -- | -- | +| @ohos.app.ability.appRecovery.d.ts | appRecovery | saveAppState(context?: UIAbilityContext): boolean; | 新增 | + +**适配指导** + +通过调用saveAppState传入UIAbility Context参数主动保存此指定的Ability的状态。 + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +onBackground() { + hilog.info(0x0000, '[demo]', '%{public}s', 'EntryAbility onBackground'); + appRecovery.saveAppState(this.context) +} +``` +## cl.ability.appRecovery新增setRestartWant接口 + +新增接口setRestartWant(want: Want): void; + +**变更影响** + +基于OpenHarmony4.0.5.2及之后的SDK版本开发的应用,可以使用setRestartWant接口设置下次由恢复主动拉起场景下的Ability。 + +**关键接口/组件变更** + +@ohos.app.ability.appRecovery.d.ts中新增setRestartWant接口。 + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| -- | -- | -- | -- | +| @ohos.app.ability.appRecovery.d.ts | appRecovery | setRestartWant(want: Want): void; | 新增 | + +**适配指导** + +通过调用setRestartWant设置下次恢复到的指定Ability。 + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +Button("启动到恢复Ability") + .fontSize(40) + .fontWeight(FontWeight.Bold) + .onClick(()=> { + // set restart want + let want = { + bundleName: "ohos.samples.recovery", + abilityName: "RecoveryAbility" + }; + + appRecovery.setRestartWant(want); + }) +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-screenlock.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-screenlock.md new file mode 100644 index 0000000000000000000000000000000000000000..8e5a2fab3671eb32db8accb72d764a1194f26ff1 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-screenlock.md @@ -0,0 +1,155 @@ +# 主题框架子系统-锁屏管理服务ChangeLog + + +## cl.screenlock.1 isLocked、unlock接口使用权限变更 +从API9开始,变更为systemapi,停止对三方应用开放。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +基于此前版本开发的应用,需适配变更的js接口,变更前的接口已经不能正常使用了,否则会影响原有功能。 + +- 涉及接口 + +```js + function isLocked(): boolean; + function unlock(callback: AsyncCallback): void; + function unlock():Promise; +``` + +- 变更前: + +```js + * Checks whether the screen is currently locked. + * + * @returns Returns {@code true} if the screen is currently locked; returns {@code false} otherwise. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function isLocked(): boolean; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function unlock(callback: AsyncCallback): void; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function unlock():Promise; +``` + +- 变更后: + +```js + * Checks whether the screen is currently locked. + * + * @returns Returns {@code true} if the screen is currently locked; returns {@code false} otherwise. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.ScreenLock + * @systemapi Hide this for inner system use. + * @since 9 + */ + function isLocked(): boolean; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function unlock(callback: AsyncCallback): void; + + /** + * Unlock the screen. + * + * @returns Returns {@code true} if the screen is unlocked successfully; returns {@code false} otherwise. + * @throws {BusinessError} 13200002 - the screenlock management service is abnormal. + * @syscap SystemCapability.MiscServices.ScreenLock + * @since 9 + */ + function unlock():Promise; +``` + + +**适配指导** + +该接口变更为系统应用后,三方应用已无法使用。 +系统应用可正常使用。 +示例代码如下: + +```js + try { + let ret = screenLock.isLocked(); + console.error(`Obtain whether the screen is locked successfully , ret is: ${ret}`); + } catch (error) { + console.error(`Failed to obtain whether the screen is locked, error is : ${error.code}, ${error.message}`); + } +``` + +```js + screenlock.unlock((err, data) => { + if (err) { + console.error(`Failed to unlock the screen, because: ${err.message}`); + return; + } + console.info(`unlock the screen successfully. result: ${data}`); + }); +``` + +```js + screenlock.unlock().then((data) => { + console.info(`unlock the screen successfully. result: ${data}`); + }).catch((err) => { + console.error(`Failed to unlock the screen, because: ${err.message}`); + }); +``` + + +## cl.screenlock.2 isSecure接口废弃变更 +从API9开始,废弃此接口。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +该接口删除无法再使用,请使用进行更新使用,否则会影响原有功能。 + +- 涉及接口 + +```js + function isSecure(): boolean; +``` + +- 变更前: + +```js + function isSecure(): boolean; +``` + +- 变更后:删除接口,停止对外开放。 + + +**适配指导** + +该接口删除后无法再使用,请适配更新。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-wallpaper.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-wallpaper.md new file mode 100644 index 0000000000000000000000000000000000000000..d3b6dfdf0a1426295d9ebf5203962c3e3b3d09a6 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.5.3/changelog-wallpaper.md @@ -0,0 +1,292 @@ +# 主题框架子系统-壁纸管理服务ChangeLog + + +## cl.wallpaper.1 getColorsSync、getMinHeightSync、getMinWidthSync、restore、setImage接口使用权限变更 +从API9开始,变更为systemapi,停止对三方应用开放。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +基于此前版本开发的应用,需适配变更的js接口,变更前的接口已经不能正常使用了,否则会影响原有功能。 + +- 涉及接口 + +```js + function getColorsSync(wallpaperType: WallpaperType): Array; + function getMinHeightSync(): number; + function getMinWidthSync(): number; + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + function restore(wallpaperType: WallpaperType): Promise; + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + +- 变更前: + +```js + /** + * Obtains the wallpaper colors for the wallpaper of the specified type. Returns rgbaColor type of array callback function. + * @param wallpaperType Indicates the wallpaper type. + * @returns { Array } the Array returned by the function. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getColorsSync(wallpaperType: WallpaperType): Array; + + /** + * Obtains the minimum height of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getMinHeightSync(): number; + + /** + * Obtains the minimum width of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function getMinWidthSync(): number; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function restore(wallpaperType: WallpaperType): Promise; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @throws {BusinessError} 202 - permission verification failed, application which is not a system application uses system API. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @systemapi Hide this for inner system use. + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + +- 变更后: + +```js + /** + * Obtains the wallpaper colors for the wallpaper of the specified type. Returns rgbaColor type of array callback function. + * @param wallpaperType Indicates the wallpaper type. + * @returns { Array } the Array returned by the function. + * @throws {BusinessError} 401 - parameter error. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getColorsSync(wallpaperType: WallpaperType): Array; + + /** + * Obtains the minimum height of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getMinHeightSync(): number; + + /** + * Obtains the minimum width of the wallpaper. in pixels. returns 0 if no wallpaper has been set. + * @returns { number } the number returned by the function. + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function getMinWidthSync(): number; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Removes a wallpaper of the specified type and restores the default one. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function restore(wallpaperType: WallpaperType): Promise; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + + /** + * Sets a wallpaper of the specified type based on the uri path from a JPEG or PNG file or the pixel map of a PNG file. + * @param source Indicates the uri path from a JPEG or PNG file or the pixel map of the PNG file. + * @param wallpaperType Indicates the wallpaper type. + * @throws {BusinessError} 401 - parameter error. + * @throws {BusinessError} 201 - permission denied. + * @permission ohos.permission.SET_WALLPAPER + * @syscap SystemCapability.MiscServices.Wallpaper + * @since 9 + */ + function setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; +``` + + +**适配指导** + +该接口变更为系统应用后,三方应用已无法使用。 +系统应用可正常使用。 +示例代码如下: + +```js + try { + let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); + console.log(`success to getColorsSync: ${JSON.stringify(colors)}`); + } catch (error) { + console.error(`failed to getColorsSync because: ${JSON.stringify(error)}`); + } +``` + +```js + let minHeight = wallpaper.getMinHeightSync(); +``` + +```js + let minWidth = wallpaper.getMinWidthSync(); +``` + +```js + wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to restore.`); + }); +``` + +```js + wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to restore.`); + }).catch((error) => { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + }); +``` + +```js + // source类型为string + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); + }); +``` + +```js + // source类型为string + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); + }).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + }); +``` + + +## cl.wallpaper.2 getIdSync、getFileSync、isChangeAllowed、isUserChangeAllowed、on、off接口废弃变更 +从API9开始,废弃此接口。 + +开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +该接口删除无法再使用,请使用进行更新使用,否则会影响原有功能。 + +- 涉及接口 + +```js + function getIdSync(wallpaperType: WallpaperType): number; + function getFileSync(wallpaperType: WallpaperType): number; + function isChangeAllowed(): boolean; + function isUserChangeAllowed(): boolean; + function on(type: 'colorChange', callback: (colors: Array, wallpaperType: WallpaperType) => void): void; + function off(type: 'colorChange', callback?: (colors: Array, wallpaperType: WallpaperType) => void): void; +``` + +- 变更前: + +```js + function getIdSync(wallpaperType: WallpaperType): number; + function getFileSync(wallpaperType: WallpaperType): number; + function isChangeAllowed(): boolean; + function isUserChangeAllowed(): boolean; + function on(type: 'colorChange', callback: (colors: Array, wallpaperType: WallpaperType) => void): void; + function off(type: 'colorChange', callback?: (colors: Array, wallpaperType: WallpaperType) => void): void; +``` + +- 变更后:删除接口,停止对外开放。 + + +**适配指导** + +该接口删除后无法再使用,请适配更新。