diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 22cc1f04257781cf6a6ad63d2c310bb991e8902b..351c3199cdaec9cfb233f29eea1ed1d4f627aa92 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -9,6 +9,7 @@ - [Getting Started with Application Development](quick-start/Readme-EN.md) - [Directory Structure](quick-start/package-structure.md) - Development + - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) - Basic Feature Development - [Window Manager](windowmanager/Readme-EN.md) diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..e0fb613133dd0854672bc5e27f44dbc63d9061ca --- /dev/null +++ b/en/application-dev/ability/Readme-EN.md @@ -0,0 +1,10 @@ +# Ability Development + - [Ability Framework Overview](ability-brief.md) + - FA Model + - [FA Model Overview](fa-brief.md) + - [Page Ability Development](fa-pageability.md) + - [Service Ability Development](fa-serviceability.md) + - [Data Ability Development](fa-dataability.md) + - [FA Widget Development](fa-formability.md) + - Other + - [Ability Assistant Usage](ability-assistant-guidelines.md) diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md new file mode 100644 index 0000000000000000000000000000000000000000..89a110ed2fefaedb379bc7adffaa132dd6548721 --- /dev/null +++ b/en/application-dev/ability/fa-formability.md @@ -0,0 +1,327 @@ +# FA Widget Development + +## Widget Overview +A Form ability presents a widget, which is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. + +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget client is responsible for displaying the service widget. + +Basic concepts: +- Widget provider + The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. +- Widget client + The widget client is an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager + The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The widget client and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. + +You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget client and Widget Manager. + +The widget provider controls the widget content to display, component layout, and click events bound to components. + +## Scenario + +Form ability development refers to the development conducted by the widget provider based on the Feature Ability (FA) model(fa-brief.md). As a widget provider, you need to carry out the following operations: + +- Develop the lifecycle callback functions in **FormAbility**. +- Create a **FormBindingData** object. +- Update a widget through **FormProvider**. +- Develop the widget UI page. + +## Available APIs + +The table below describes the lifecycle callback functions provided **FormAbility**. + +**Table 1** FormAbility APIs + +| API | Description | +| :----------------------------------------------------------- | :------------------------------------------- | +| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | +| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| +| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | +| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | +| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the ability is running is updated. | + +For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). + +**Table 2** FormProvider APIs + +| API | Description | +| :----------------------------------------------------------- | :------------------------------------------------ | +| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. | +| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| +| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result. | +| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result. | + +## How to Develop + +### Creating a Form Ability + +To create a widget in the FA model, you need to implement the lifecycle callback functions of **FormAbility**. The sample code is as follows: + +1. Import the required modules. + + ```javascript + import formBindingData from '@ohos.application.formBindingData' + import formInfo from '@ohos.application.formInfo' + import formProvider from '@ohos.application.formProvider' + ``` + +2. Implement the lifecycle callback functions of **FormAbility**. + + ```javascript + export default { + onCreate(want) { + console.log('FormAbility onCreate'); + // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + }, + onCastToNormal(formId) { + // Called when the widget client converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + console.log('FormAbility onCastToNormal'); + }, + onUpdate(formId) { + // To support scheduled update, periodic update, or update requested by the widget client for a widget, override this method for data update. + console.log('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.log('FormAbility updateForm, error:' + JSON.stringify(error)); + }); + }, + onVisibilityChange(newStatus) { + // Called when the widget client initiates an event about visibility changes. The widget provider should do something to respond to the notification. + console.log('FormAbility onVisibilityChange'); + }, + onEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.log('FormAbility onEvent'); + }, + onDestroy(formId) { + // Delete widget data. + console.log('FormAbility onDestroy'); + }, + onAcquireFormState(want) { + console.log('FormAbility onAcquireFormState'); + return formInfo.FormState.READY; + }, + } + ``` + +### Configuring config.json for the Form Ability + +Configure the **config.json** file for the **Form** ability. + +- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows: + + | Field| Description | Data Type| Default | + | -------- | ------------------------------------------------------------ | -------- | ------------------------ | + | name | Name of a JavaScript component. The default value is **default**. | String | No | + | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | + | window | Window-related configurations. This field applies only to phones, tablets, smart TVs, head units, and wearable devices.| Object | Yes | + | type | Type of the JavaScript component. Available values are as follows:
**normal**: indicates that the JavaScript component is an application instance.
**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| + | mode | Development mode of the JavaScript component. | Object | Yes (initial value: left empty) | + + A configuration example is as follows: + + ```json + "js": [{ + "name": "widget", + "pages": ["pages/index/index"], + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "type": "form" + }] + ``` + +- The **abilities** module in the **config.json** file corresponds to the **Form** ability. The internal field structure is described as follows: + + | Field | Description | Data Type | Default | + | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | + | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | + | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | + | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | + | type | Type of the widget. Available values are as follows:
**Java**: indicates a Java-programmed widget.
**JS**: indicates a JavaScript-programmed widget.| String | No | + | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | + | landscapeLayouts | Landscape layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | + | portraitLayouts | Portrait layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | + | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | + | formConfigAbility | Name of the facility or activity used to adjust a widget. | String | Yes (initial value: left empty) | + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | + | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This field is required only by JavaScript-programmed widgets.| String | No | + | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | + | customizeData | Custom information about the widget. | Object array | Yes (initial value: left empty) | + + A configuration example is as follows: + + ```json + "abilities": [{ + "name": "FormAbility", + "description": "This is a FormAbility", + "formsEnabled": true, + "icon": "$media:icon", + "label": "$string:form_FormAbility_label", + "srcPath": "FormAbility", + "type": "service", + "forms": [{ + "colorMode": "auto", + "defaultDimension": "2*2", + "description": "This is a service widget.", + "formVisibleNotify": true, + "isDefault": true, + "jsComponentName": "widget", + "name": "widget", + "scheduledUpdateTime": "10:30", + "supportDimensions": ["2*2"], + "type": "JS", + "updateDuration": 1, + "updateEnabled": true + }] + }] + ``` + + +### Widget Data Persistence + +Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. + +```javascript + onCreate(want) { + console.log('FormAbility onCreate'); + + let formId = want.parameters["ohos.extra.param.key.form_identity"]; + let formName = want.parameters["ohos.extra.param.key.form_name"]; + let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; + // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + storeFormInfo(formId, formName, tempFlag, want); + + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + } +``` + +You should override **onDestroy** to delete widget data. + +```javascript + onDestroy(formId) { + // Delete widget data. + deleteFormInfo(formId); + console.log('FormAbility onDestroy'); + } +``` + +For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). + +Note that the **Want** passed by the widget client to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. + +Normal widget: a widget that will be persistently used by the widget client + +Temporary widget: a widget that is temporarily used by the widget client + +Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget client may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. + +### Developing the Widget UI Page +You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. + + - HML: + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + + - CSS: + + ```css +.container { + flex-direction: column; + justify-content: center; + align-items: center; +} + +.bg-img { + flex-shrink: 0; + height: 100%; +} + +.container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; +} + +.title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; +} + +.detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; +} + ``` + + - JSON: + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "com.example.MyApplication.hmservice.FormAbility", + "params": { + "message": "add detail" + } + } + } + } + ``` + +Now you've got a widget shown below. + +![fa-form-example](figures/fa-form-example.png) diff --git a/en/application-dev/application-dev-website.md b/en/application-dev/application-dev-website.md new file mode 100644 index 0000000000000000000000000000000000000000..f2367108230f24f71b60d0570855d9c251fb5b7f --- /dev/null +++ b/en/application-dev/application-dev-website.md @@ -0,0 +1,583 @@ +- [Application Development Overview](application-dev-guide.md) +- Quick Start + - Getting Started with Application Development + - DevEco Studio (OpenHarmony) User Guide + - [Overview](quick-start/deveco-studio-overview.md) + - [Version Change History](quick-start/deveco-studio-release-notes.md) + - [Configuring the OpenHarmony SDK](quick-start/configuring-openharmony-sdk.md) + - Creating an OpenHarmony Project + - [Using the Project Wizard to Create a Project](quick-start/use-wizard-to-create-project.md) + - [Importing a Sample to Create a Project](quick-start/import-sample-to-create-project.md) + - [Configuring the OpenHarmony App Signature](quick-start/configuring-openharmony-app-signature.md) + - [Installing and Running Your OpenHarmony App](quick-start/installing-openharmony-app.md) + - [Directory Structure](quick-start/package-structure.md) + - [Resource File Categories](quick-start/basic-resource-file-categories.md) +- Development + - [Ability Development](ability/Readme-EN.md) + - [Ability Framework Overview](ability/ability-brief.md) + - FA Model + - [FA Model Overview](ability/fa-brief.md) + - [Page Ability Development](ability/fa-pageability.md) + - [Service Ability Development](ability/fa-serviceability.md) + - [Data Ability Development](ability/fa-dataability.md) + - [FA Widget Development](ability/fa-formability.md) + + - Other + - [Ability Assistant Usage](ability/ability-assistant-guidelines.md) + - [UI]](ui/Readme-EN.md) + - JavaScript-based Web-Like Development Paradigm + - [Overview](ui/ui-js-overview.md) + - Framework + - [File Organization](ui/js-framework-file.md) + - ["js" Tag](ui/js-framework-js-tag.md) + - [app.js](ui/js-framework-js-file.md) + - Syntax + - [HML](ui/js-framework-syntax-hml.md) + - [CSS](ui/js-framework-syntax-css.md) + - [JavaScript](ui/js-framework-syntax-js.md) + - [Lifecycle](ui/js-framework-lifecycle.md) + - [Resource Limitations and Access](ui/js-framework-resource-restriction.md) + - [Multi-Language Capability](ui/js-framework-multiple-languages.md) + - Building the UI + - [Component Overview](ui/ui-js-building-ui-component.md) + - Building the Layout + - [Layout Description](ui/ui-js-building-ui-layout-intro.md) + - [Adding Title and Paragraph Text](ui/ui-js-building-ui-layout-text.md) + - [Adding an Image](ui/ui-js-building-ui-layout-image.md) + - [Adding a Comment](ui/ui-js-building-ui-layout-comment.md) + - [Adding a Container](ui/ui-js-building-ui-layout-external-container.md) + - [Adding Interactions](ui/ui-js-building-ui-interactions.md) + - [Developing Animations](ui/ui-js-building-ui-animation.md) + - [Defining Events](ui/ui-js-building-ui-event.md) + - [Defining Page Routes](ui/ui-js-building-ui-routes.md) + - Common Component Development Guidelines + - Container Components + - [List](ui/ui-js-components-list.md) + - [Dialog](ui/ui-js-components-dialog.md) + - [Form](ui/ui-js-components-form.md) + - [Stepper](ui/ui-js-components-stepper.md) + - [Tabs](ui/ui-js-component-tabs.md) + - Basic Components + - [Text](ui/ui-js-components-text.md) + - [Input](ui/ui-js-components-input.md) + - [Button](ui/ui-js-components-button.md) + - [Picker](ui/ui-js-components-picker.md) + - [Image](ui/ui-js-components-images.md) + - Animation Development Guidelines + - CSS Animation + - [Defining Attribute Style Animations](ui/ui-js-animate-attribute-style.md) + - [Defining Animations with the transform Attribute](ui/ui-js-animate-transform.md) + - [Defining Animations with the background-position Attribute](ui/ui-js-animate-background-position-style.md) + - JS Animation + - [Component Animation](ui/ui-js-animate-component.md) + - Interpolator Animation + - [Animation Effect](ui/ui-js-animate-dynamic-effects.md) + - [Animation Frame](ui/ui-js-animate-frame.md) + - [Custom Components](ui/ui-js-custom-components.md) + - TypeScript-based Declarative Development Paradigm + - [Overview](ui/ui-ts-overview.md) + - Framework Overview + - File Organization + - [Directory Structure](ui/ts-framework-directory.md) + - [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md) + - ["js" Tag](ui/ts-framework-js-tag.md) + - Resource Access + - [Media Resource Types](ui/ts-media-resource-type.md) + - [Pixel Units](ui/ts-pixel-units.md) + - [Types](ui/ts-types.md) + - Declarative Syntax + - [Overview](ui/ts-syntax-intro.md) + - General UI Description Specifications + - [Basic Concepts](ui/ts-general-ui-concepts.md) + - Declarative UI Description Specifications + - [Parameterless Configuration](ui/ts-parameterless-configuration.md) + - [Configuration with Mandatory Parameters](ui/ts-configuration-with-mandatory-parameters.md) + - [Attribution Configuration](ui/ts-attribution-configuration.md) + - [Event Configuration](ui/ts-event-configuration.md) + - [Child Component Configuration](ui/ts-child-component-configuration.md) + - Componentization + - [@Component](ui/ts-component-based-component.md) + - [@Entry](ui/ts-component-based-entry.md) + - [@Preview](ui/ts-component-based-preview.md) + - [@Builder](ui/ts-component-based-builder.md) + - [@Extend](ui/ts-component-based-extend.md) + - [@CustomDialog](ui/ts-component-based-customdialog.md) + - About UI State Management + - [Basic Concepts](ui/ts-ui-state-mgmt-concepts.md) + - Managing Component States + - [@State](ui/ts-component-states-state.md) + - [@Prop](ui/ts-component-states-prop.md) + - [@Link](ui/ts-component-states-link.md) + - Managing Application States + - [AppStorage](ui/ts-application-states-appstorage.md) + - [PersistentStorage](ui/ts-application-states-apis-persistentstorage.md) + - [Environment](ui/ts-application-states-apis-environment.md) + - Managing Other States + - [@observed and @objectLink](ui/ts-other-states-observed-objectlink.md) + - [@Consume and @Provide](ui/ts-other-states-consume-provide.md) + - [@Watch](ui/ts-other-states-watch.md) + - About Rendering Control Syntax + - [if/else](ui/ts-rending-control-syntax-if-else.md) + - [ForEach](ui/ts-rending-control-syntax-foreach.md) + - [LazyForEach](ui/ts-rending-control-syntax-lazyforeach.md) + - About @Component + - [build Function](ui/ts-function-build.md) + - [Custom Component Initialization](ui/ts-custom-component-initialization.md) + - [Custom Component Lifecycle Callbacks](ui/ts-custom-component-lifecycle-callbacks.md) + - [Example: Component Creation and Re-Initialization](ui/ts-component-creation-re-initialization.md) + - [Syntactic Sugar](ui/ts-syntactic-sugar.md) + - Experiencing the Declarative UI + - [Creating a Declarative UI Project](ui/ui-ts-creating-project.md) + - [Getting to Know Components](ui/ui-ts-components.md) + - [Creating a Simple Page](ui/ui-ts-creating-simple-page.md) + - Defining Page Layout and Connection + - [Building a Food Data Model](ui/ui-ts-building-data-model.md) + - [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) + - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) + - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) + - Basic Functions + - Window Manager + - Window + - [Window Overview](windowmanager/window-overview.md) + - [Window Development](windowmanager/window-guidelines.md) + - Display + - [Display Overview](windowmanager/display-overview.md) + - [Display Development](windowmanager/display-guidelines.md) + - Screenshot + - [Screenshot Overview](windowmanager/screenshot-overview.md) + - [Screenshot Development](windowmanager/screenshot-guidelines.md) + - WebGL + - [WebGL Overview](webgl/webgl-overview.md) + - [WebGL Development](webgl/webgl-guidelines.md) + - Media + - Audio + - [Audio Overview](media/audio-overview.md) + - [Audio Playback Development](media/audio-playback.md) + - [Audio Playback Development Using AudioRenderer](media/audio-renderer.md) + - [Audio Recording Development](media/audio-recorder.md) + - [Audio Recorder Development Using AudioCapturer](media/audio-capturer) + - Video + - [Video Playback Development](media/video-playback.md) + - [Video Recording Development](media/video-recorder.md) + - Image + - [Image Development](media/image.md) + - Security + - User Authentication + - [User Authentication Overview](security/userauth-overview.md) + - [User Authentication Development](security/userauth-guidelines.md) + - hapsigner + - [hapsigner Guide](security/hapsigntool-guidelines.md) + - Connectivity + - IPC & RPC + - [IPC & RPC Overview](connectivity/ipc-rpc-overview.md) + - [IPC & RPC Development Guidelines](connectivity/ipc-rpc-development-guideline.md) + - [Subscribing to State Changes of a Remote Object](connectivity/subscribe-remote-state.md) + - Data Management + - Distributed Data Service + - [Distributed Data Service Overview](database/database-mdds-overview.md) + - [Distributed Data Service Development](database/database-mdds-guidelines.md) + - Relational Database Overview + - [RDB Overview](database/database-relational-overview.md) + - [RDB Development](database/database-relational-guidelines.md) + - Lightweight Data Store + - [Lightweight Data Store Overview](database/database-preference-overview.md) + - [Lightweight Data Store Development](database/database-preference-guidelines.md) + - Agent-Powered Scheduled Reminders + - [Overview](background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md) + - [Development Guidelines](background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md) + - Background Task Management + - [Background Task Management Overview](background-task-management/background-task-overview.md) + - [Background Task Management Development](background-task-management/background-task-dev-guide.md) + - Device + - USB Service + - [USB Service Overview](device/usb-overview.md) + - [USB Service Development](device/usb-guidelines.md) + - Location + - [Location Overview](device/device-location-overview.md) + - [Obtaining Device Location Information](device/device-location-info.md) + - [Geocoding and Reverse Geocoding Capabilities](device/device-location-geocoding.md) + - Sensor + - [Sensor Overview](device/sensor-overview.md) + - [Sensor Development](device/sensor-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-dev-guide.md) + - DFX + - Application Event Logging + - [Overview of Application Event Logging](dfx/hiappevent-overview.md) + - [Development Guidelines on Application Event Logging](dfx/hiappevent-guidelines.md) + - Performance Tracing + - [Overview of Performance Tracing](dfx/hitracemeter-overview.md) + - [Development of Performance Tracing](dfx/hitracemeter-guidelines.md) + - Distributed Call Chain Tracing + - [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md) + - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) +- Tools + - DevEco Studio (OpenHarmony) User Guide + - [Overview](quick-start/deveco-studio-overview.md) + - [Version Change History](quick-start/deveco-studio-release-notes.md) + - [Configuring the OpenHarmony SDK](quick-start/configuring-openharmony-sdk.md) + - [Creating an OpenHarmony Project](quick-start/create-openharmony-project.md) + - [Configuring the OpenHarmony App Signature](quick-start/configuring-openharmony-app-signature.md) + - [Installing and Running Your OpenHarmony App](quick-start/installing-openharmony-app.md) +- Hands-On Tutorials + - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) +- API References + - Compent Reference (JavaScript-based Web-like Development Paradigm) + - Components + - Common + - [Universal Attributes](reference/arkui-js/js-components-common-attributes.md) + - [Universal Styles](reference/arkui-js/js-components-common-styles.md) + - [Universal Events](reference/arkui-js/js-components-common-events.md) + - [Universal Methods](reference/arkui-js/js-components-common-methods.md) + - [Animation Styles](reference/arkui-js/js-components-common-animation.md) + - [Gradient Styles](reference/arkui-js/js-components-common-gradient.md) + - [Transition Styles](reference/arkui-js/js-components-common-transition.md) + - [Custom Font Styles](reference/arkui-js/js-components-common-customizing-font.md) + - [Atomic Layout](reference/arkui-js/js-components-common-atomic-layout.md) + - Container Components + - [badge](reference/arkui-js/js-components-container-badge.md) + - [dialog](reference/arkui-js/js-components-container-dialog.md) + - [div](reference/arkui-js/js-components-container-div.md) + - [form](reference/arkui-js/js-components-container-form.md) + - [list](reference/arkui-js/js-components-container-list.md) + - [list-item](reference/arkui-js/js-components-container-list-item.md) + - [list-item-group](reference/arkui-js/js-components-container-list-item-group.md) + - [panel](reference/arkui-js/js-components-container-panel.md) + - [popup](reference/arkui-js/js-components-container-popup.md) + - [refresh](reference/arkui-js/js-components-container-refresh.md) + - [stack](reference/arkui-js/js-components-container-stack.md) + - [stepper](reference/arkui-js/js-components-container-stepper.md) + - [stepper-item](reference/arkui-js/js-components-container-stepper-item.md) + - [swiper](reference/arkui-js/js-components-container-swiper.md) + - [tabs](reference/arkui-js/js-components-container-tabs.md) + - [tab-bar](reference/arkui-js/js-components-container-tab-bar.md) + - [tab-content](reference/arkui-js/js-components-container-tab-content.md) + - Basic Components + - [button](reference/arkui-js/js-components-basic-button.md) + - [chart](reference/arkui-js/js-components-basic-chart.md) + - [divider](reference/arkui-js/js-components-basic-divider.md) + - [image](reference/arkui-js/js-components-basic-image.md) + - [image-animator](reference/arkui-js/js-components-basic-image-animator.md) + - [input](reference/arkui-js/js-components-basic-input.md) + - [label](reference/arkui-js/js-components-basic-label.md) + - [marquee](reference/arkui-js/js-components-basic-marquee.md) + - [menu](reference/arkui-js/js-components-basic-menu.md) + - [option](reference/arkui-js/js-components-basic-option.md) + - [picker](reference/arkui-js/js-components-basic-picker.md) + - [picker-view](reference/arkui-js/js-components-basic-picker-view.md) + - [piece](reference/arkui-js/js-components-basic-piece.md) + - [progress](reference/arkui-js/js-components-basic-progress.md) + - [qrcode](reference/arkui-js/js-components-basic-qrcode.md) + - [rating](reference/arkui-js/js-components-basic-rating.md) + - [richtext](reference/arkui-js/js-components-basic-richtext.md) + - [search](reference/arkui-js/js-components-basic-search.md) + - [select](reference/arkui-js/js-components-basic-select.md) + - [slider](reference/arkui-js/js-components-basic-slider.md) + - [span](reference/arkui-js/js-components-basic-span.md) + - [switch](reference/arkui-js/js-components-basic-switch.md) + - [text](reference/arkui-js/js-components-basic-text.md) + - [textarea](reference/arkui-js/js-components-basic-textarea.md) + - [toolbar](reference/arkui-js/js-components-basic-toolbar.md) + - [toolbar-item](reference/arkui-js/js-components-basic-toolbar-item.md) + - [toggle](reference/arkui-js/js-components-basic-toggle.md) + - [web](reference/arkui-js/js-components-basic-web.md) + - Media Components + - [video](reference/arkui-js/js-components-media-video.md) + - Canvas Components + - [canvas](reference/arkui-js/js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md) + - [Image](reference/arkui-js/js-components-canvas-image.md) + - [CanvasGradient](reference/arkui-js/js-components-canvas-canvasgradient.md) + - [ImageData](reference/arkui-js/js-components-canvas-imagedata.md) + - [Path2D](reference/arkui-js/js-components-canvas-path2d.md) + - [ImageBitmap](reference/arkui-js/js-components-canvas-imagebitmap.md) + - [OffscreenCanvas](reference/arkui-js/js-components-canvas-offscreencanvas.md) + - [OffscreenCanvasRenderingContext2D](reference/arkui-js/js-offscreencanvasrenderingcontext2d.md) + - Grid + - [Basic Concepts](reference/arkui-js/js-components-grid-basic-concepts.md) + - [grid-container](reference/arkui-js/js-components-grid-container.md) + - [grid-row](reference/arkui-js/js-components-grid-row.md) + - [grid-col](reference/arkui-js/js-components-grid-col.md) + - SVG Components + - [Universal Attributes](reference/arkui-js/js-components-svg-common-attributes.md) + - [svg](reference/arkui-js/js-components-svg.md) + - [rect](reference/arkui-js/js-components-svg-rect.md) + - [circle](reference/arkui-js/js-components-svg-circle.md) + - [ellipse](reference/arkui-js/js-components-svg-ellipse.md) + - [path](reference/arkui-js/js-components-svg-path.md) + - [line](reference/arkui-js/js-components-svg-line.md) + - [polyline](reference/arkui-js/js-components-svg-polyline.md) + - [polygon](reference/arkui-js/js-components-svg-polygon.md) + - [text](reference/arkui-js/js-components-svg-text.md) + - [tspan](reference/arkui-js/js-components-svg-tspan.md) + - [textPath](reference/arkui-js/js-components-svg-textpath.md) + - [animate](reference/arkui-js/js-components-svg-animate.md) + - [animateMotion](reference/arkui-js/js-components-svg-animatemotion.md) + - [animateTransform](reference/arkui-js/js-components-svg-animatetransform.md) + - Custom Components + - [Basic Usage](reference/arkui-js/js-components-custom-basic-usage.md) + - [Custom Events](reference/arkui-js/js-components-custom-events.md) + - [props](reference/arkui-js/js-components-custom-props.md) + - [Event Parameter](reference/arkui-js/js-components-custom-event-parameter.md) + - [slot](reference/arkui-js/js-components-custom-slot.md) + - [Lifecycle Definition](reference/arkui-js/js-components-custom-lifecycle.md) + - Appendix + - [Type Attributes](reference/arkui-js/js-appendix-types.md) + - Compent Reference (TypeScript-based Declarative Development Paradigm) + - Components + - Universal Components + - Universal Events + - [Click Event](reference/arkui-ts/ts-universal-events-click.md) + - [Touch](reference/arkui-ts/ts-universal-events-touch.md) + - [Show/Hide Event](reference/arkui-ts/ts-universal-events-show-hide.md) + - [Drag/Drop Event](reference/arkui-ts/ts-universal-events-drag-drop.md) + - [Key Event](reference/arkui-ts/ts-universal-events-key.md) + - [Focus Event](reference/arkui-ts/ts-universal-focus-event.md) + - [Mouse Event](reference/arkui-ts/ts-universal-mouse-key.md) + - [Component Area Change Event](reference/arkui-ts/ts-universal-events-component-area-change.md) + - Universal Attributes + - [Size](reference/arkui-ts/ts-universal-attributes-size.md) + - [Location](reference/arkui-ts/ts-universal-attributes-location.md) + - [Layout Constraints](reference/arkui-ts/ts-universal-attributes-layout-constraints.md) + - [Flex Layout](reference/arkui-ts/ts-universal-attributes-flex-layout.md) + - [Border Configuration](reference/arkui-ts/ts-universal-attributes-border.md) + - [Background](reference/arkui-ts/ts-universal-attributes-background.md) + - [Opacity](reference/arkui-ts/ts-universal-attributes-opacity.md) + - [Visibility](reference/arkui-ts/ts-universal-attributes-visibility.md) + - [Enable/Disable](reference/arkui-ts/ts-universal-attributes-enable.md) + - [Overlay](reference/arkui-ts/ts-universal-attributes-overlay.md) + - [Z-order Control](reference/arkui-ts/ts-universal-attributes-z-order.md) + - [Transformation](reference/arkui-ts/ts-universal-attributes-transformation.md) + - [Image Effect Configuration](reference/arkui-ts/ts-universal-attributes-image-effect.md) + - [Shape Clipping](reference/arkui-ts/ts-universal-attributes-sharp-clipping.md) + - [Text Style](reference/arkui-ts/ts-universal-attributes-text-style.md) + - [Grid](reference/arkui-ts/ts-universal-attributes-grid.md) + - [Gradient Color](reference/arkui-ts/ts-universal-attributes-gradient-color.md) + - [Popup Control](reference/arkui-ts/ts-universal-attributes-popup.md) + - [Menu Control](reference/arkui-ts/ts-universal-attributes-menu.md) + - [Click Control](reference/arkui-ts/ts-universal-attributes-click.md) + - [Focus Control](reference/arkui-ts/ts-universal-attributes-focus.md) + - [Hover Effect](reference/arkui-ts/ts-universal-attributes-hover-effect.md) + - [Component ID](reference/arkui-ts/ts-universal-attributes-component-id.md) + - [Touch Target](reference/arkui-ts/ts-universal-attributes-touch-target.md) + - [Polymorphic Style](reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) + - Gesture Processing + - [Gesture Binding Methods](reference/arkui-ts/ts-gesture-settings.md) + - Basic Gestures + - [TapGesture](reference/arkui-ts/ts-basic-gestures-tapgesture.md) + - [LongPressGesture](reference/arkui-ts/ts-basic-gestures-longpressgesture.md) + - [PanGesture](reference/arkui-ts/ts-basic-gestures-pangesture.md) + - [PinchGesture](reference/arkui-ts/ts-basic-gestures-pinchgesture.md) + - [RotationGesture](reference/arkui-ts/ts-basic-gestures-rotationgesture.md) + - [SwipeGesture](reference/arkui-ts/ts-basic-gestures-swipegesture.md) + - [Combined Gestures](reference/arkui-ts/ts-combined-gestures.md) + - Basic Components + - [Blank](reference/arkui-ts/ts-basic-components-blank.md) + - [Button](reference/arkui-ts/ts-basic-components-button.md) + - [Checkbox](reference/arkui-ts/ts-basic-components-checkbox.md) + - [CheckboxGroup](reference/arkui-ts/ts-basic-components-checkboxgroup.md) + - [DataPanel](reference/arkui-ts/ts-basic-components-datapanel.md) + - [DatePicker](reference/arkui-ts/ts-basic-components-datepicker.md) + - [Divider](reference/arkui-ts/ts-basic-components-divider.md) + - [Image](reference/arkui-ts/ts-basic-components-image.md) + - [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) + - [Progress](reference/arkui-ts/ts-basic-components-progress.md) + - [QRCode](reference/arkui-ts/ts-basic-components-qrcode.md) + - [Radio](reference/arkui-ts/ts-basic-components-radio.md) + - [Rating](reference/arkui-ts/ts-basic-components-rating.md) + - [Select](reference/arkui-ts/ts-basic-components-select.md) + - [Slider](reference/arkui-ts/ts-basic-components-slider.md) + - [Span](reference/arkui-ts/ts-basic-components-span.md) + - [Text](reference/arkui-ts/ts-basic-components-text.md) + - [TextArea](reference/arkui-ts/ts-basic-components-textarea.md) + - [TextInput](reference/arkui-ts/ts-basic-components-textinput.md) + - [TextTimer](reference/arkui-ts/ts-basic-components-texttimer.md) + - [Toggle](reference/arkui-ts/ts-basic-components-toggle.md) + - [TextClock](reference/arkui-ts/ts-basic-components-textclock.md) + - [Web](reference/arkui-ts/ts-basic-components-web.md) + - Container Components + - [AlphabetIndexer](reference/arkui-ts/ts-container-alphabet-indexer.md) + - [Badge](reference/arkui-ts/ts-container-badge.md) + - [Column](reference/arkui-ts/ts-container-column.md) + - [ColumnSplit](reference/arkui-ts/ts-container-columnsplit.md) + - [Counter](reference/arkui-ts/ts-container-counter.md) + - [Flex](reference/arkui-ts/ts-container-flex.md) + - [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md) + - [Grid](reference/arkui-ts/ts-container-grid.md) + - [GridItem](reference/arkui-ts/ts-container-griditem.md) + - [List](reference/arkui-ts/ts-container-list.md) + - [ListItem](reference/arkui-ts/ts-container-listitem.md) + - [Navigator](reference/arkui-ts/ts-container-navigator.md) + - [Navigation](reference/arkui-ts/ts-container-navigation.md) + - [Panel](reference/arkui-ts/ts-container-panel.md) + - [Row](reference/arkui-ts/ts-container-row.md) + - [RowSplit](reference/arkui-ts/ts-container-rowsplit.md) + - [Scroll](reference/arkui-ts/ts-container-scroll.md) + - [ScrollBar](reference/arkui-ts/ts-container-scrollbar.md) + - [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md) + - [Stack](reference/arkui-ts/ts-container-stack.md) + - [Swiper](reference/arkui-ts/ts-container-swiper.md) + - [Tabs](reference/arkui-ts/ts-container-tabs.md) + - [TabContent](reference/arkui-ts/ts-container-tabcontent.md) + - [Refresh](reference/arkui-ts/ts-container-refresh.md) + - Media Components + - [Video](reference/arkui-ts/ts-media-components-video.md) + - Drawing Components + - [Circle](reference/arkui-ts/ts-drawing-components-circle.md) + - [Ellipse](reference/arkui-ts/ts-drawing-components-ellipse.md) + - [Line](reference/arkui-ts/ts-drawing-components-line.md) + - [Polyline](reference/arkui-ts/ts-drawing-components-polyline.md) + - [Polygon](reference/arkui-ts/ts-drawing-components-polygon.md) + - [Path](reference/arkui-ts/ts-drawing-components-path.md) + - [Rect](reference/arkui-ts/ts-drawing-components-rect.md) + - [Shape](reference/arkui-ts/ts-drawing-components-shape.md) + - Canvas Components + - [Canvas](reference/arkui-ts/ts-components-canvas-canvas.md) + - [CanvasRenderingContext2D](reference/arkui-ts/ts-canvasrenderingcontext2d.md) + - [OffscreenCanvasRenderingConxt2D](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) + - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) + - [Path2D](reference/arkui-ts/ts-components-canvas-path2d.md) + - [CanvasGradient](reference/arkui-ts/ts-components-canvas-canvasgradient.md) + - [ImageBitmap](reference/arkui-ts/ts-components-canvas-imagebitmap.md) + - [ImageData](reference/arkui-ts/ts-components-canvas-imagedata.md) + - Animation + - [Attribute Animation](reference/arkui-ts/ts-animatorproperty.md) + - [Explicit Animation](reference/arkui-ts/ts-explicit-animation.md) + - Transition Animation + - [Page Transition](reference/arkui-ts/ts-page-transition-animation.md) + - [Component Transition](reference/arkui-ts/ts-transition-animation-component.md) + - [Transition of Shared Elements](reference/arkui-ts/ts-transition-animation-shared-elements.md) + - [Motion Path Animation](reference/arkui-ts/ts-motion-path-animation.md) + - [Matrix Transformation](reference/arkui-ts/ts-matrix-transformation.md) + - [Interpolation Calculation](reference/arkui-ts/ts-interpolation-calculation.md) + - Global UI Methods + - [Image Cache](reference/arkui-ts/ts-methods-image-cache.md) + - Dialog Box + - [Alert Dialog Box](reference/arkui-ts/ts-methods-alert-dialog-box.md) + - [Action Sheet](reference/arkui-ts/ts-methods-action-sheet.md) + - [Custom Dialog Box](reference/arkui-ts/ts-methods-custom-dialog-box.md) + - [Date Picker Dialog Box](reference/arkui-ts/ts-methods-datepicker-dialog.md) + - [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md) + - [Menu](reference/arkui-ts/ts-methods-menu.md) + - Appendix + - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) + - APIs + - Ability Framework + - [FeatureAbility Module](reference/apis/js-apis-featureAbility.md) + - [ParticleAbility Module](reference/apis/js-apis-particleAbility.md) + - [DataAbilityHelper Module](reference/apis/js-apis-dataAbilityHelper.md) + - [DataUriUtils Module](reference/apis/js-apis-DataUriUtils.md) + - [Bundle Module](reference/apis/js-apis-Bundle.md) + - [Context Module](reference/apis/js-apis-Context.md) + - Event Notification + - [CommonEvent Module](reference/apis/js-apis-commonEvent.md) + - [Notification Module](reference/apis/js-apis-notification.md) + - [Reminder Agent](reference/apis/js-apis-reminderAgent.md) + - Resource Management + - [Resource Manager](reference/apis/js-apis-resource-manager.md) + - [Internationalization (intl)](reference/apis/js-apis-intl.md) + - [Internationalization (i18n)](reference/apis/js-apis-i18n.md) + - Media + - [Audio Management](reference/apis/js-apis-audio.md) + - [Media](reference/apis/js-apis-media.md) + - [Image Processing](reference/apis/js-apis-image.md) + - [Camera](reference/apis/js-apis-camera.md) + - Security + - [User Authentication](reference/apis/js-apis-useriam-userauth.md) + - [Access Control](reference/apis/js-apis-abilityAccessCtrl.md) + - Data Management + - [Lightweight Storage](reference/apis/js-apis-data-preferences.md) + - [Distributed Data Management](reference/apis/js-apis-distributed-data.md) + - [Relational Database](reference/apis/js-apis-data-rdb.md) + - [Result Set](reference/apis/js-apis-data-resultset.md) + - [DataAbilityPredicates](reference/apis/js-apis-data-ability.md) + - [Settings](reference/apis/js-apis-settings.md) + - File Management + - [File Management](reference/apis/js-apis-fileio.md) + - [Statfs](reference/apis/js-apis-statfs.md) + - [Environment](reference/apis/js-apis-environment.md) + - [Public File Access and Management](reference/apis/js-apis-filemanager.md) + - [App Storage Statistics](reference/apis/js-apis-storage-statistics.md) + - [Volume Management](reference/apis/js-apis-volumemanager.md) + - Account Management + - [OS Account Management](reference/apis/js-apis-osAccount.md) + - [Distributed Account Management](reference/apis/js-apis-distributed-account.md) + - [App Account Management](reference/apis/js-apis-appAccount.md) + - Telephony Service + - [Call](reference/apis/js-apis-call.md) + - [SMS](reference/apis/js-apis-sms.md) + - [SIM Management](reference/apis/js-apis-sim.md) + - [Radio](reference/apis/js-apis-radio.md) + - [Observer](reference/apis/js-apis-observer.md) + - [Cellular Data](reference/apis/js-apis-telephony-data.md) + - Network Management + - [Network Connection Management](js-apis-net-connection.md) + - [Socket Connection](js-apis-socket.md) + - [WebSocket Connection](js-apis-webSocket.md) + - [Data Request](js-apis-http.md) + - Network and Connectivity + - [WLAN](reference/apis/js-apis-wifi.md) + - [Bluetooth](reference/apis/js-apis-bluetooth.md) + - [RPC](reference/apis/js-apis-rpc.md) + - Device Management + - [Sensor](reference/apis/js-apis-sensor.md) + - [Vibrator](reference/apis/js-apis-vibrator.md) + - [Brightness](reference/apis/js-apis-brightness.md) + - [Battery Info](reference/apis/js-apis-battery-info.md) + - [Power Management](reference/apis/js-apis-power.md) + - [Thermal Management](reference/apis/js-apis-thermal.md) + - [Running Lock](reference/apis/js-apis-runninglock.md) + - [Device Info](reference/apis/js-apis-device-info.md) + - [systemParameter](reference/apis/js-apis-system-parameter.md) + - [Device Management](reference/apis/js-apis-device-manager.md) + - [Window](reference/apis/js-apis-window.md) + - [Display](reference/apis/js-apis-display.md) + - [Update](reference/apis/js-apis-update.md) + - [USB](reference/apis/js-apis-usb.md) + - [Location](reference/apis/js-apis-geolocation.md) + - Basic Features + - [Application Context](reference/apis/js-apis-basic-features-app-context.md) + - [Console Logs](reference/apis/js-apis-basic-features-logs.md) + - [Page Routing](reference/apis/js-apis-basic-features-routes.md) + - [Timer](reference/apis/js-apis-basic-features-timer.md) + - [Setting the System Time](reference/apis/js-apis-system-time.md) + - [Animation](reference/apis/js-apis-basic-features-animator.md) + - [WebGL](reference/apis/js-apis-webgl.md) + - [WebGL2](reference/apis/js-apis-webgl2.md) + - [Screenshot](reference/apis/js-apis-screenshot.md) + - [Accessibility](reference/apis/js-apis-accessibility.md) + - DFX + - [HiAppEvent](reference/apis/js-apis-hiappevent.md) + - [Performance Tracing](reference/apis/js-apis-hitracemeter.md) + - [Fault Logger](reference/apis/js-apis-faultLogger.md) + - [Distributed Call Chain Tracing](reference/apis/js-apis-hitracechain.md) + - [HiLog](reference/apis/js-apis-hilog.md) + - [HiChecker](reference/apis/js-apis-hichecker.md) + - [HiDebug](reference/apis/js-apis-hidebug.md) + - Language Base Class Library + - [Obtaining Process Information](reference/apis/js-apis-process.md) + - [URL String Parsing](reference/apis/js-apis-url.md) + - [URI String Parsing](reference/apis/js-apis-uri.md) + - [Util](reference/apis/js-apis-util.md) + - [XML Parsing and Generation](reference/apis/js-apis-xml.md) + - [XML-to-JavaScript Conversion](reference/apis/js-apis-convertxml.md) + - [Worker Startup](reference/apis/js-apis-worker.md) + - [Linear Container ArrayList](reference/apis/js-apis-arraylist.md) + - [Linear Container Deque](reference/apis/js-apis-deque.md) + - [Linear Container List](reference/apis/js-apis-list.md) + - [Linear Container LinkedList](reference/apis/js-apis-linkedlist.md) + - [Linear Container Queue](reference/apis/js-apis-queue.md) + - [Linear Container Stack](reference/apis/js-apis-stack.md) + - [Linear Container Vector](reference/apis/js-apis-vector.md) + - [Nonlinear Container HashSet](reference/apis/js-apis-hashset.md) + - [Nonlinear Container HashMap](reference/apis/js-apis-hashmap.md) + - [Nonlinear Container PlainArray](reference/apis/js-apis-plainarray.md) + - [Nonlinear Container TreeMap](reference/apis/js-apis-treemap.md) + - [Nonlinear Container TreeSet](reference/apis/js-apis-treeset.md) + - [Nonlinear Container LightWeightMap](reference/apis/js-apis-lightweightmap.md) + - [Nonlinear Container LightWeightSet](reference/apis/js-apis-lightweightset.md) + - Custom Management + - [Configuration Policy](reference/apis/js-apis-config-policy.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index b33bcf666262b6c1b98d4ed734c08b4a2a6d03bc..8deb55f2e962ec65a9fc44f4b260d71c1d34f158 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -18,12 +18,14 @@ - Media - [Audio Management](js-apis-audio.md) - [Media](js-apis-media.md) + - [Image Processing](js-apis-image.md) + - [Camera](js-apis-camera.md) - Security - [User Authentication](js-apis-useriam-userauth.md) - [Access Control](js-apis-abilityAccessCtrl.md) - Data Management - [Lightweight Storage9+](js-apis-data-preferences.md) - - [Lightweight Storage](js-apis-data-storage.md) + - [Lightweight Storage](js-apis-data-storage.md) - [Distributed Data Management](js-apis-distributed-data.md) - [Relational Database](js-apis-data-rdb.md) - [Result Set](js-apis-data-resultset.md) @@ -76,8 +78,6 @@ - [Application Context](js-apis-basic-features-app-context.md) - [Console Logs](js-apis-basic-features-logs.md) - [Page Routing](js-apis-basic-features-routes.md) - - [Pop-up Window](js-apis-basic-features-pop-up.md) - - [Application Configuration](js-apis-basic-features-configuration.md) - [Timer](js-apis-basic-features-timer.md) - [Setting the System Time](js-apis-system-time.md) - [Animation](js-apis-basic-features-animator.md) diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index a9eca8e2656bc76830215358751cee5af4000e63..71f5f2a90b50513c194c3dad027b86abcb296984 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -143,7 +143,7 @@ Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to **Parameters:** | Name | Type | Mandatory | Description | | :--------- | :---------------------------------------------- | :-------- | :--------------------------------------------------- | -| options | [AudioCapturerOptions](#AudioCapturerOptions) | Yes | Capturer configurations. | +| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations. | | callback | AsyncCallback<[AudioCapturer](#audiocapturer8)> | Yes | Callback used to return the audio capturer instance. | **Example:** @@ -189,7 +189,7 @@ Obtains an **AudioCapturer** instance. This API uses a promise to return the cap **Parameters:** | Name | Type | Mandatory | Description | | :--------- | :-------------------------------------------- | :-------- | :-------------------------- | -| options | [AudioCapturerOptions](#AudioCapturerOptions) | Yes | Capturer configurations. | +| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations. | **Return value:** @@ -516,6 +516,32 @@ Describes audio renderer configuration options. | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. | | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Renderer information. | +## AudioCapturerInfo8+ + +Describes audio capturer information. + +**System capability:** SystemCapability.Multimedia.Audio.Core + +**Parameters:** + +| Name | Type | Mandatory | Description | +| :---------------| :------------------------- | :-------- | :-------------------- | +| source | [SourceType](#sourcetype) | Yes | Audio source type. | +| capturerFlags | number | Yes | Audio capturer flags. | + +## AudioCapturerOptions8+ + +Describes audio capturer configuration options. + +**System capability:** SystemCapability.Multimedia.Audio.Capturer + +**Parameters:** + +| Name | Type | Mandatory | Description | +| :------------ | :-----------------------------------------| :-------- | :-------------------- | +| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Capturer information. | + ## InterruptEvent9+ Describes the interrupt event received by the app when playback is interrupted. @@ -556,7 +582,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. It will be a | ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | actionType | [InterruptActionType](#interruptactiontype) | Yes | Event return type. TYPE_ACTIVATED is the audio interrupt activated event, and TYPE_INTERRUPT is the audio interrupt event. | | type | [InterruptType](#interrupttype) | No | Interrupt event type. | -| hint | [InterruptHint](interrupthint) | No | Interrupt event prompts. | +| hint | [InterruptHint](#interrupthint) | No | Interrupt event prompts. | | activated | boolean | No | Acquire/release focus. true indicates that the focus acquisition/release is successful, and false indicates that the focus acquisition/release fails. | ## VolumeEvent8+ @@ -584,8 +610,8 @@ Describes the device change type and device information. | Name | Type | Mandatory | Description | | :------------------ | :------------------------------------------------ | :-------- | :------------------ | -| type | [DeviceChangeType](#DeviceChangeType) | Yes | Device change type. | -| deviceDescriptors | [AudioDeviceDescriptors](#AudioDeviceDescriptors) | Yes | Device information. | +| type | [DeviceChangeType](#devicechangetype) | Yes | Device change type. | +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | ## DeviceChangeType @@ -599,21 +625,6 @@ Enumerates device change types. | CONNECT | 0 | Device connection. | | DISCONNECT | 1 | Device disconnection. | - -## AudioCapturerInfo8+ - -Describes audio capturer information. - -**System capability:** SystemCapability.Multimedia.Audio.Core - -**Parameters:** - -| Name | Type | Mandatory | Description | -| :---------------| :------------------------- | :-------- | :-------------------- | -| source | [SourceType](#sourcetype) | Yes | Audio source type. | -| capturerFlags | number | Yes | Audio capturer flags. | - - ## SourceType8+ Enumerates source types. @@ -1614,7 +1625,7 @@ Subscribes to device change events. When a device is connected/disconnected, reg | Name | Type | Mandatory | Description | | :------- | :-------------------------------------------------- | :---------| :---------------------------------------------------------------------------------------------------------------------------------------------- | | type | string | Yes | Type of the event to subscribe to. The value 'deviceChange' means the device change event, which is triggered when a device change is detected. | -| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | Yes | Callback used to obtain the device update details. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | Yes | Callback used to obtain the device update details. | **Example:** @@ -1642,7 +1653,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. It will be a | Name | Type | Mandatory | Description | | :------- | :-------------------------------------------------- | :---------| :-------------------------------------------------- | | type | string | Yes | Type of the event to unsubscribe from. | -| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | Yes | Callback used to obtain the device update details. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to obtain the device update details. | **Example:** @@ -2701,7 +2712,7 @@ Subscribes to state change events. | Name | Type | Mandatory | Description | | :------- | :------------------------- | :-------- | :--------------------------------------------------------------------------------------- | | type | string | Yes | Type of the event to subscribe to. The value 'stateChange' means the state change event. | -| callback | [AudioState](#AudioState8) | Yes | Callback used to return the state change. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example:** @@ -2751,7 +2762,7 @@ Obtains the capturer information provided while creating a capturer instance. Th | Name | Type | Mandatory | Description | | :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioCapturerInfo](#audioCapturerInfo)\> | Yes | Callback used to return the capturer information. | +| callback | AsyncCallback<[AudioCapturerInfo](#audiocapturerinfo)\> | Yes | Callback used to return the capturer information. | **Example:** @@ -2812,7 +2823,7 @@ Obtains the capturer stream information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | :------- | :----------------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#AudioRendererOptions8)\> | Yes | Callback used to return the stream information. | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example:** @@ -2842,7 +2853,7 @@ Obtains the capturer stream information. This API uses a promise to return the r | Type | Description | | :---------------------------------------------------- | :----------------------------------------------- | -| Promise<[AudioStreamInfo](#AudioRendererOptions8)\> | Promise used to return the stream information. | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example:** @@ -3058,7 +3069,6 @@ Reads the buffer from the audio capturer. This API uses an asynchronous callback audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { console.log("Success in reading the buffer data"); - var number = fileio.writeSync(fd, buffer); } }; ``` @@ -3311,7 +3321,7 @@ Subscribes to state change events. | Name | Type | Mandatory | Description | | :------- | :------------------------- | :-------- | :--------------------------------------------------------------------------------------- | | type | string | Yes | Type of the event to subscribe to. The value 'stateChange' means the state change event. | -| callback | [AudioState](#AudioState8) | Yes | Callback used to return the state change. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example:** diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index 9f8cef0aa5104d9d858ce559d78348fc2f88bf9e..f74e565b2d2dda5aa0421d5a7629e5fbee4dbdd5 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1311,7 +1311,7 @@ Disconnects an A2DP connection. ```js let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); -let boolean ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); +let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index c3ee9fdace8184109ddb62d58be87c3c30d99ac7..da7f0ae7bbac41be20f73b958f92317756e4de1e 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,250 +1,140 @@ -# Reminder Agent +# Reminder Agent ->**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. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import +## Modules to Import ``` -import reminderAgent from '@ohos.reminderAgent'; +import reminderAgent from'@ohos.reminderAgent'; ``` -## System Capabilities - -SystemCapability.Notification.ReminderAgent - -## Required Permissions - -ohos.permission.PUBLISH\_AGENT\_REMINDER - -## reminderAgent.publishReminder - -publishReminder\(reminderReq: ReminderRequest, callback: AsyncCallback\): void - -Publishes an agent-powered reminder. This method uses an asynchronous callback to return the published reminder's ID. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderReq

-

ReminderRequest

-

Yes

-

Reminder to be published.

-

callback

-

AsyncCallback<number>

-

Yes

-

Asynchronous callback used to return the result.

-
- -- Example - - ``` - export default { - data: { - timer: { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 3 - } - }, - startTimer() { - reminderAgent.publishReminder(timer, (err, reminderId) => { - console.log("reminderId = " + reminderId); - }); - } - } - ``` - - -## reminderAgent.publishReminder - -publishReminder\(reminderReq: ReminderRequest\): Promise - -Publishes an agent-powered reminder. This method uses a promise callback to return the published reminder's ID. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderReq

-

ReminderRequest

-

Yes

-

Reminder to be published.

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

Type

-

Description

-

Promise<number>

-

Promise used to return the result.

-
- -- Example - - ``` - export default { - data: { - timer: { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 3 - } - }, - startTimer() { - reminderAgent.publishReminder(this.timer).then((reminderId) => { - console.log("reminderId = " + reminderId); - }); - } - } - ``` - - -## reminderAgent.cancelReminder - -cancelReminder\(reminderId: number, callback: AsyncCallback\): void - -Cancels the reminder with the specified ID. This method uses an asynchronous callback to return the cancellation result. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderId

-

number

-

Yes

-

ID of the reminder to cancel.

-

callback

-

AsyncCallback<void>

-

Yes

-

Asynchronous callback used to return the result.

-
- -- Example + +## Required Permissions + +ohos.permission.PUBLISH_AGENT_REMINDER + + +## reminderAgent.publishReminder + +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void + +Publishes an agent-powered reminder. This API uses an asynchronous callback to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| + | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + +- Example + ``` + export default { data: {timer: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + }, + startTimer() { + reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("reminderId = " + reminderId); + }); + } + } + ``` + + +## reminderAgent.publishReminder + +publishReminder(reminderReq: ReminderRequest): Promise<number> + +Publishes an agent-powered reminder. This API uses a promise callback to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the published reminder's ID.| + +- Example + ``` + export default { data: {timer: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + }, + startTimer() { + reminderAgent.publishReminder(this.timer).then((reminderId) => { + console.log("reminderId = " + reminderId); + }); + } + } + ``` + + +## reminderAgent.cancelReminder + +cancelReminder(reminderId: number, callback: AsyncCallback<void>): void + +Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderId | number | Yes| ID of the reminder to cancel.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| + +- Example ``` export default { - cancel() { - reminderAgent.cancelReminder(1, (err, data) => { + cancel() { reminderAgent.cancelReminder(1, (err, data) => { console.log("do next"); }); } } ``` -## reminderAgent.cancelReminder - -cancelReminder\(reminderId: number\): Promise - -Cancels the reminder with the specified ID. This method uses a promise to return the cancellation result. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderId

-

number

-

Yes

-

ID of the reminder to cancel.

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

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
- -- Example + +## reminderAgent.cancelReminder + +cancelReminder(reminderId: number): Promise<void> + +Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderId | number | Yes| ID of the reminder to cancel.| + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +- Example ``` export default { @@ -256,38 +146,24 @@ export default { } ``` -## reminderAgent.getValidReminders - -getValidReminders\(callback: AsyncCallback\>\): void - -Obtains all valid \(not yet expired\) reminders set by the current application. This method uses an asynchronous callback to return the reminders. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<Array<ReminderRequest>>

-

Yes

-

Asynchronous callback used to return an array of all valid reminders set by the current application.

-
- -- Example + +## reminderAgent.getValidReminders + +getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void + +Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| + +- Example ``` reminderAgent.getValidReminders((err, reminders) => { @@ -315,30 +191,24 @@ reminderAgent.getValidReminders((err, reminders) => { }) ``` -## reminderAgent.getValidReminders -getValidReminders\(\): Promise\> +## reminderAgent.getValidReminders + +getValidReminders(): Promise<Array<ReminderRequest>> + +Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. -Obtains all valid \(not yet expired\) reminders set by the current application. This method uses a promise to return the reminders. +- System capability -- Return values + SystemCapability.Notification.ReminderAgent - - - - - - - - - -

Type

-

Description

-

Promise<Array<ReminderRequest>>

-

Promise used to return an array of all valid reminders set by the current application.

-
+- Return value -- Example +| Type| Description| +| -------- | -------- | +| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| + +- Example ``` reminderAgent.getValidReminders().then((reminders) => { @@ -366,126 +236,79 @@ reminderAgent.getValidReminders().then((reminders) => { }) ``` -## reminderAgent.cancelAllReminders - -cancelAllReminders\(callback: AsyncCallback\): void - -Cancels all reminders set by the current application. This method uses an asynchronous callback to return the cancellation result. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<void>

-

Yes

-

Asynchronous callback used to return the result.

-
- -- Example + +## reminderAgent.cancelAllReminders + +cancelAllReminders(callback: AsyncCallback<void>): void + +Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| + +- Example ``` reminderAgent.cancelAllReminders((err, data) =>{ - console.log("do next")} -) + console.log("do next")}) ``` -## reminderAgent.cancelAllReminders -cancelAllReminders\(\): Promise +## reminderAgent.cancelAllReminders -Cancels all reminders set by the current application. This method uses a promise to return the cancellation result. +cancelAllReminders(): Promise<void> -- Return values +Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
+- System capability -- Example + SystemCapability.Notification.ReminderAgent + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +- Example ``` reminderAgent.cancelAllReminders().then(() => { - console.log("do next")} -) + console.log("do next")}) ``` -## reminderAgent.addNotificationSlot - -addNotificationSlot\(slot: NotificationSlot, callback: AsyncCallback\): void - -Adds a reminder notification slot. This method uses an asynchronous callback to return the result. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

slot

-

NotificationSlot

-

Yes

-

Reminder notification slot to add.

-

callback

-

AsyncCallback<void>

-

Yes

-

Asynchronous callback used to return the result.

-
- -- Example + +## reminderAgent.addNotificationSlot + +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void + +Adds a reminder notification slot. This API uses an asynchronous callback to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| + +- Example ``` -export default { - data: { - mySlot: { +export default { data: { mySlot: { type: 3, sound: "/sdcard/music2.mp3" - } - }, + } }, addSlot() { reminderAgent.addNotificationSlot(this.mySlot, (err, data) => { console.log("do next"); @@ -494,685 +317,246 @@ export default { } ``` -## reminderAgent.addNotificationSlot - -addNotificationSlot\(slot: NotificationSlot\): Promise - -Adds a reminder notification slot. This method uses a promise to return the result. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

slot

-

NotificationSlot

-

Yes

-

Reminder notification slot to add.

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

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
- -- Example + +## reminderAgent.addNotificationSlot + +addNotificationSlot(slot: NotificationSlot): Promise<void> + +Adds a reminder notification slot. This API uses a promise to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +- Example ``` -export default { - data: { - mySlot: { +export default { data: { mySlot: { type: 3, sound: "/sdcard/music2.mp3" - } - }, + } }, addSlot() { reminderAgent.addNotificationSlot(this.mySlot).then(() => { - console.log("do next"); + console.log("do next"); }); } } ``` -## reminderAgent.removeNotificationSlot - -removeNotificationSlot\(slotType: notification.SlotType, callback: AsyncCallback\): void - -Removes a **NotificationSlot** instance of a specified type. This method uses an asynchronous callback to return the result. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

slotType

-

notification.SlotType

-

Yes

-

Type of the reminder notification slot to remove.

-

callback

-

AsyncCallback<void>

-

Yes

-

Asynchronous callback used to return the result.

-
- -- Example + +## reminderAgent.removeNotificationSlot + +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void + +Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| + +- Example ``` export default { - removeSlot() { - reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { + removeSlot() {reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { console.log("do next"); - }); +}); } } ``` -## reminderAgent.removeNotificationSlot - -removeNotificationSlot\(slotType: notification.SlotType\): Promise - -Removes a **NotificationSlot** instance of a specified type. This method uses a promise to return the result. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

slotType

-

notification.SlotType

-

Yes

-

Type of the reminder notification slot to remove.

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

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
- -- Example + +## reminderAgent.removeNotificationSlot + +removeNotificationSlot(slotType: notification.SlotType): Promise<void> + +Removes a notification slot of a specified type. This API uses a promise to return the result. + +- System capability + + SystemCapability.Notification.ReminderAgent + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +- Example ``` export default { - removeSlot() { - reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { + removeSlot() { reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { console.log("do next"); }); } } ``` -## ActionButtonType + +## ActionButtonType Enumerates button types. - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

ACTION_BUTTON_TYPE_CLOSE

-

0

-

Button for closing the reminder.

-

ACTION_BUTTON_TYPE_SNOOZE

-

1

-

Button for snoozing the reminder.

-
- -## ReminderType +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| ACTION_BUTTON_TYPE_CLOSE | 0 | Button for closing the reminder.| +| ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| + + +## ReminderType Enumerates reminder types. - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

REMINDER_TYPE_TIMER

-

0

-

Countdown reminder.

-

REMINDER_TYPE_CALENDAR

-

1

-

Calendar reminder.

-

REMINDER_TYPE_ALARM

-

2

-

Alarm reminder.

-
- -## ActionButton +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| REMINDER_TYPE_TIMER | 0 | Countdown reminder.| +| REMINDER_TYPE_CALENDAR | 1 | Calendar reminder.| +| REMINDER_TYPE_ALARM | 2 | Alarm reminder.| + + +## ActionButton Defines a button displayed in the reminder notification. - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

title

-

string

-

Yes

-

Text on the button.

-

type

-

ActionButtonType

-

Yes

-

Button type.

-
- -## WantAgent +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| title | string | Yes| Text on the button.| +| type | [ActionButtonType](#actionbuttontype) | Yes| Button type.| + + +## WantAgent Sets the package and ability that are redirected to when the reminder notification is clicked. - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

pkgName

-

string

-

Yes

-

Name of the package redirected to when the reminder notification is clicked.

-

abilityName

-

string

-

Yes

-

Name of the ability that is redirected to when the reminder notification is clicked.

-
- -## MaxScreenWantAgent +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| + + +## MaxScreenWantAgent Sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

pkgName

-

string

-

Yes

-

Name of the package that is automatically started when the reminder arrives and the device is not in use.

-

abilityName

-

string

-

Yes

-

Name of the ability that is automatically started when the reminder arrives and the device is not in use.

-
- -## ReminderRequest +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| + + +## ReminderRequest Defines the reminder to publish. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderType

-

ReminderType

-

Yes

-

Type of the reminder.

-

actionButton

-

[ActionButton?, ActionButton?]

-

No

-

Action button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)

-

wantAgent

-

WantAgent

-

No

-

Information about the ability that is redirected to when the notification is clicked.

-

maxScreenWantAgent

-

MaxScreenWantAgent

-

No

-

Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.

-

ringDuration

-

number

-

No

-

Ringing duration.

-

snoozeTimes

-

number

-

No

-

Number of reminder snooze times.

-

timeInterval

-

number

-

No

-

Reminder snooze interval.

-

title

-

string

-

No

-

Reminder title.

-

content

-

string

-

No

-

Reminder content.

-

expiredContent

-

string

-

No

-

Content to be displayed after the reminder expires.

-

snoozeContent

-

string

-

No

-

Content to be displayed when the reminder is snoozing.

-

notificationId

-

number

-

No

-

Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.

-

slotType

-

notification.SlotType

-

No

-

Type of the slot used by the reminder.

-
- -## ReminderRequestCalendar +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderType | ReminderType | Yes| Type of the reminder.| +| actionButton | [ActionButton?, ActionButton?] | No| Action button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| +| wantAgent | WantAgent | No| Information about the ability that is redirected to when the notification is clicked.| +| maxScreenWantAgent | MaxScreenWantAgent | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| +| ringDuration | number | No| Ringing duration.| +| snoozeTimes | number | No| Number of reminder snooze times.| +| timeInterval | number | No| Reminder snooze interval.| +| title | string | No| Reminder title.| +| content | string | No| Reminder content.| +| expiredContent | string | No| Content to be displayed after the reminder expires.| +| snoozeContent | string | No| Content to be displayed when the reminder is snoozing.| +| notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | No| Type of the slot used by the reminder.| + + +## ReminderRequestCalendar ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

dateTime

-

LocalDateTime

-

Yes

-

Reminder time.

-

repeatMonths

-

Array<number>

-

No

-

Month in which the reminder repeats.

-

repeatDays

-

Array<number>

-

No

-

Date on which the reminder repeats.

-
- -## ReminderRequestAlarm +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| +| repeatMonths | Array<number> | No| Month in which the reminder repeats.| +| repeatDays | Array<number> | No| Date on which the reminder repeats.| + + +## ReminderRequestAlarm ReminderRequestAlarm extends ReminderRequest -Defines a reminder for the alarm clock. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

hour

-

number

-

Yes

-

Hour portion of the reminder time.

-

minute

-

number

-

Yes

-

Minute portion of the reminder time.

-

daysOfWeek

-

Array<number>

-

No

-

Days of a week when the reminder repeats.

-
- -## ReminderRequestTimer - -Defines a **ReminderRequestTimer** instance, which extends **ReminderRequest**. +Defines a reminder for an alarm. + +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description:| +| -------- | -------- | -------- | -------- | +| hour | number | Yes| Hour portion of the reminder time.| +| minute | number | Yes| Minute portion of the reminder time.| +| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats.| + + +## ReminderRequestTimer + +ReminderRequestTimer extends ReminderRequest Defines a reminder for a scheduled timer. - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

triggerTimeInSeconds

-

number

-

Yes

-

Number of seconds in the countdown timer.

-
- -## LocalDateTime +- **System capability**: SystemCapability.Notification.ReminderAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| triggerTimeInSeconds | number | Yes| Number of seconds in the countdown timer.| + + +## LocalDateTime 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.

-
+- **System capability**: SystemCapability.Notification.ReminderAgent + +| 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.| 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 5205bc6c9bdf5cbb741258be4425d032fab454a7..7af90e99d9b1b57f167acb10de07c8bffbc5875c 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,4 +1,4 @@ -# Resource Management +Resource Management > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,12 +18,12 @@ Obtains the **ResourceManager** object of this application. This method uses a c **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes| Callback used to return the **ResourceManager** object obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------- | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { if (error != null) { @@ -49,13 +49,13 @@ Obtains the **ResourceManager** object of an application. This method uses an as **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the target application.| - | callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes| Callback used to return the **ResourceManager** object obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------- | +| bundleName | string | Yes | Bundle name of the target application. | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| -- Example +**Example** ``` resourceManager.getResourceManager("com.example.myapplication", (error, mgr) => { }); @@ -70,12 +70,12 @@ Obtains the **ResourceManager** object of this application. This method uses a p **System capability**: SystemCapability.Global.ResourceManager -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +**Return value** +| Type | Description | +| ---------------------------------------- | ----------------- | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| -- Example +**Example** ``` resourceManager.getResourceManager().then(mgr => { mgr.getString(0x1000000, (error, value) => { @@ -99,22 +99,22 @@ Obtains the **ResourceManager** object of an application. This method uses a pro **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the target application.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| bundleName | string | Yes | Bundle name of the target application.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +**Return value** +| Type | Description | +| ---------------------------------------- | ------------------ | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| -- Example +**Example** ``` resourceManager.getResourceManager("com.example.myapplication").then(mgr => { - + }).catch(error => { - + }); ``` @@ -123,72 +123,82 @@ Obtains the **ResourceManager** object of an application. This method uses a pro Enumerates the screen directions. -| Name| Default Value| Description| -| -------- | -------- | -------- | -| DIRECTION_VERTICAL | 0 | Portrait
**System capability**: SystemCapability.Global.ResourceManager| -| DIRECTION_HORIZONTAL | 1 | Landscape
**System capability**: SystemCapability.Global.ResourceManager| +**System capability**: SystemCapability.Global.ResourceManager + +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DIRECTION_VERTICAL | 0 | Portrait | +| DIRECTION_HORIZONTAL | 1 | Landscape | ## DeviceType Enumerates the device types. -| Name| Default Value| Description| -| -------- | -------- | -------- | -| DEVICE_TYPE_PHONE | 0x00 | Mobile phone.
**System capability**: SystemCapability.Global.ResourceManager| -| DEVICE_TYPE_TABLET | 0x01 | Tablet.
**System capability**: SystemCapability.Global.ResourceManager| -| DEVICE_TYPE_CAR | 0x02 | Automobile.
**System capability**: SystemCapability.Global.ResourceManager| -| DEVICE_TYPE_PC | 0x03 | Computer.
**System capability**: SystemCapability.Global.ResourceManager| -| DEVICE_TYPE_TV | 0x04 | TV.
**System capability**: SystemCapability.Global.ResourceManager| -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable.
**System capability**: SystemCapability.Global.ResourceManager| +**System capability**: SystemCapability.Global.ResourceManager + +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DEVICE_TYPE_PHONE | 0x00 | Mobile phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Automobile. | +| DEVICE_TYPE_PC | 0x03 | Computer. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity Enumerates the screen density types. -| Name| Default Value| Description| -| -------- | -------- | -------- | -| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI).
**System capability**: SystemCapability.Global.ResourceManager| -| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI).
**System capability**: SystemCapability.Global.ResourceManager| -| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI).
**System capability**: SystemCapability.Global.ResourceManager| -| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI).
**System capability**: SystemCapability.Global.ResourceManager| -| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI).
**System capability**: SystemCapability.Global.ResourceManager| -| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).
**System capability**: SystemCapability.Global.ResourceManager| +**System capability**: SystemCapability.Global.ResourceManager + +| Name | Default Value | Description | +| -------------- | ---- | ---------- | +| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI). | +| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI). | +| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI). | +| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI). | +| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI). | +| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).| ## Configuration Defines the device configuration. +**System capability**: SystemCapability.Global.ResourceManager + -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| direction | [Direction](#direction) | Yes| No| Screen direction of the device.
**System capability**: SystemCapability.Global.ResourceManager| -| locale | string | Yes| No| Current system language.
**System capability**: SystemCapability.Global.ResourceManager| +| Name | Type | Readable | Writable | Description | +| --------- | ----------------------- | ---- | ---- | -------- | +| direction | [Direction](#direction) | Yes | No | Screen direction of the device.| +| locale | string | Yes | No | Current system language. | ## DeviceCapability Defines the device capability. +**System capability**: SystemCapability.Global.ResourceManager + -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| screenDensity | [ScreenDensity](#screendensity) | Yes| No| Screen density of the device.
**System capability**: SystemCapability.Global.ResourceManager| -| deviceType | [DeviceType](#devicetype) | Yes| No| Type of the device.
**System capability**: SystemCapability.Global.ResourceManager| +| Name | Type | Readable | Writable | Description | +| ------------- | ------------------------------- | ---- | ---- | -------- | +| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | ## RawFileDescriptor8+ -Defines the descriptor information of the raw file. -
**System capability**: SystemCapability.Global.ResourceManager +Defines the descriptor information of the raw file.
+**System capability**: SystemCapability.Global.ResourceManager -| Name| Type| Description| -| -------- | -------- | -------- | -| fd | number | Descriptor of a raw file.| -| offset | number | Offset to the start position of the raw file.| -| length | number | Length of the raw file.| +| Name | Type | Description | +| ------ | ------ | ------------------ | +| fd | number | Descriptor of a raw file.| +| offset | number | Offset to the start position of the raw file. | +| length | number | Length of the raw file. | ## ResourceManager @@ -197,7 +207,7 @@ Defines the capability of accessing application resources. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - 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**. @@ -209,13 +219,13 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | callback | AsyncCallback<string> | Yes| Callback used to return the string obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the string obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id, (error, value) => { @@ -237,17 +247,17 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the string obtained.| +**Return value** +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | Promise used to return the string obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id).then(value => { @@ -267,13 +277,13 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | callback | AsyncCallback<Array<string>> | Yes| Callback used to return the obtained array of strings.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the obtained array of strings.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id, (error, value) => { @@ -295,17 +305,17 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<Array<string>> | Promise used to return the array of strings obtained.| +**Return value** +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the array of strings obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id).then(value => { @@ -325,13 +335,13 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | callback | AsyncCallback<Uint8Array> | Yes| Callback used to return the content of the media file obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the content of the media file obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id, (error, value) => { @@ -353,17 +363,17 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<Uint8Array> | Promise used to return the content of the media file obtained.| +**Return value** +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id).then(value => { @@ -383,13 +393,13 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | callback | AsyncCallback<string> | Yes| Callback used to return the Base64 code of the image obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the Base64 code of the image obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id, (error, value) => { @@ -411,17 +421,17 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the Base64 code of the image obtained.| +**Return value** +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the Base64 code of the image obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id).then(value => { @@ -441,12 +451,12 @@ Obtains the device configuration. This method uses an asynchronous callback to r **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Configuration](#configuration)> | Yes| Callback used to return the obtained device configuration.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the obtained device configuration.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { @@ -468,12 +478,12 @@ Obtains the device configuration. This method uses a promise to return the resul **System capability**: SystemCapability.Global.ResourceManager -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| +**Return value** +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration().then(value => { @@ -493,12 +503,12 @@ Obtains the device capability. This method uses an asynchronous callback to retu **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes| Callback used to return the obtained device capability.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the obtained device capability.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { @@ -520,12 +530,12 @@ Obtains the device capability. This method uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| +**Return value** +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability().then(value => { @@ -545,14 +555,14 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | num | number | Yes| Number that determines the plural or singular form.| - | callback | AsyncCallback<string> | Yes| Callback used to return the singular-plural string obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | Yes | Resource ID. | +| num | number | Yes | Number that determines the plural or singular form. | +| callback | AsyncCallback<string> | Yes | Callback used to return the singular-plural string obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { @@ -574,18 +584,18 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | resId | number | Yes| Resource ID.| - | num | number | Yes| Number that determines the plural or singular form.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| num | number | Yes | Number that determines the plural or singular form. | -- Return value - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the singular-plural string obtained.| +**Return value** +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the singular-plural string obtained.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1).then(value => { @@ -604,13 +614,13 @@ Obtains the content of the raw file in the specified path. This method uses an a **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| - | callback | AsyncCallback<Uint8Array> | Yes| Callback used to return the raw file content, in byte arrays.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the raw file content, in byte arrays.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml", (error, value) => { @@ -631,17 +641,17 @@ Obtains the content of the raw file in the specified path. This method uses a pr **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| +**Return value** +| Type | Description | +| ------------------------- | ----------- | +| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml").then(value => { @@ -660,13 +670,13 @@ Obtains the descriptor of the raw file in the specified path. This method uses a **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| - | callback | AsyncCallback<[RawFileDescriptor](#RawFileDescriptor8+)> | Yes| Callback used to return the raw file descriptor.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8+ { mgr.getRawFileDescriptor("test.xml", (error, value) => { @@ -689,17 +699,17 @@ Obtains the descriptor of the raw file in the specified path. This method uses a **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[RawFileDescriptor](#RawFileDescriptor8+)> | Promise used to return the raw file descriptor.| +**Return value** +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the raw file descriptor.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFileDescriptor("test.xml").then(value => { @@ -720,13 +730,13 @@ Closes the descriptor of the raw file in the specified path. This method uses an **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------- | +| path | string | Yes | Path of the raw file.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml", (error, value) => { @@ -745,17 +755,17 @@ Closes the descriptor of the raw file in the specified path. This method uses a **System capability**: SystemCapability.Global.ResourceManager -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the raw file.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | No value is returned.| +**Return value** +| Type | Description | +| ------------------- | ---- | +| Promise<void> | No value is returned.| -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml").then(value => { @@ -768,13 +778,13 @@ Closes the descriptor of the raw file in the specified path. This method uses a ### release7+ -release(); +release() Releases the created **resourceManager**. **System capability**: SystemCapability.Global.ResourceManager -- Example +**Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.release((error, value) => { diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 8a938bb7530dac245723ba11a35e485afaf024e1..0f57a0ac5c6754d9e5673086a47beee9fc775ffe 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,7 +1,7 @@ -# RPC Communication +# RPC -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -13,11 +13,6 @@ import rpc from '@ohos.rpc'; ``` -## Required Permissions - -None - - ## MessageParcel Provides methods for reading and writing basic data types and arrays, inter-process communication (IPC) objects, interface tokens, and sequenceable objects. @@ -29,14 +24,15 @@ create(): MessageParcel Creates a **MessageParcel** object. This method is a static method. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | MessageParcel | **MessageParcel** object created. | + | MessageParcel | **MessageParcel** object created.| - Example - + ``` let data = rpc.MessageParcel.create(); console.log("RpcClient: data is " + data); @@ -47,11 +43,12 @@ Creates a **MessageParcel** object. This method is a static method. reclaim(): void -Reclaims the **MessageParcel** instance that is no longer used. +Reclaims the **MessageParcel** object that is no longer used. +**System capability**: SystemCapability.Communication.IPC.Core - Example - + ``` let reply = rpc.MessageParcel.create(); reply.reclaim(); @@ -63,18 +60,21 @@ Reclaims the **MessageParcel** instance that is no longer used. writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean Serializes a remote object and writes it to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageParcel** object. | + | object | [IRemoteObject](#iremoteobject) | Yes| Remote object to serialize and write to the **MessageParcel** object.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -93,14 +93,15 @@ readRemoteObject(): IRemoteObject Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | [IRemoteObject](#iremoteobject) | Remote object obtained. | + | [IRemoteObject](#iremoteobject) | Remote object obtained.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -120,19 +121,20 @@ writeInterfaceToken(token: string): boolean Writes an interface token to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | token | string | Yes | Interface token to write. | + | token | string | Yes| Interface token to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeInterfaceToken("aaa"); @@ -146,14 +148,15 @@ readInterfaceToken(): string Reads the interface token from this **MessageParcel** object. The interface tokens are read in the order in which they are written into the **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | Interface token obtained. | + | string | Interface token obtained.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -171,14 +174,15 @@ getSize(): number Obtains the data size of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Data size obtained, in bytes. | + | number | Size of the **MessageParcel** object obtained, in bytes.| - Example - + ``` let data = rpc.MessageParcel.create(); let size = data.getSize(); @@ -192,14 +196,15 @@ getCapacity(): number Obtains the capacity of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **MessageParcel** capacity obtained, in bytes. | + | number | **MessageParcel** capacity obtained, in bytes.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.getCapacity(); @@ -213,19 +218,20 @@ setSize(size: number): boolean Sets the size of data contained in this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | size | number | Yes | Data size to set, in bytes. | + | size | number | Yes| Data size to set, in bytes.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let setSize = data.setSize(16); @@ -239,19 +245,20 @@ setCapacity(size: number): boolean Sets the storage capacity of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | size | number | Yes | Storage capacity to set, in bytes. | + | size | number | Yes| Storage capacity to set, in bytes.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.setCapacity(100); @@ -265,14 +272,15 @@ getWritableBytes(): number Obtains the writable capacity of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **MessageParcel** writable capacity obtained, in bytes. | + | number | **MessageParcel** writable capacity obtained, in bytes.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -290,14 +298,15 @@ getReadableBytes(): number Obtains the readable capacity of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **MessageParcel** readable capacity obtained, in bytes. | + | number | **MessageParcel** object readable capacity, in bytes.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -315,14 +324,15 @@ getReadPosition(): number Obtains the read position of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Current read position of the **MessageParcel** object. | + | number | Current read position of the **MessageParcel** object.| - Example - + ``` let data = rpc.MessageParcel.create(); let readPos = data.getReadPosition(); @@ -336,14 +346,15 @@ getWritePosition(): number Obtains the write position of this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Current write position of the **MessageParcel** object. | + | number | Current write position of the **MessageParcel** object.| - Example - + ``` let data = rpc.MessageParcel.create(); data.writeInt(10); @@ -358,19 +369,20 @@ rewindRead(pos: number): boolean Moves the read pointer to the specified position. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | pos | number | Yes | Position from which data is to read. | + | pos | number | Yes| Position from which data is to read.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the read position changes; returns **false** otherwise. | + | boolean | Returns **true** if the read position changes; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); data.writeInt(12); @@ -389,19 +401,20 @@ rewindWrite(pos: number): boolean Moves the write pointer to the specified position. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | pos | number | Yes | Position from which data is to write. | + | pos | number | Yes| Position from which data is to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the write position changes; returns **false** otherwise. | + | boolean | Returns **true** if the write position changes; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); data.writeInt(4); @@ -416,21 +429,22 @@ Moves the write pointer to the specified position. writeByte(val: number): boolean -Writes a **Byte** value to this **MessageParcel** object. +Writes a Byte value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Byte** value to write. | + | val | number | Yes| Byte value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeByte(2); @@ -442,16 +456,17 @@ Writes a **Byte** value to this **MessageParcel** object. readByte(): number -Reads the **Byte** value from this **MessageParcel** object. +Reads the Byte value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Byte** value read. | + | number | Byte value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeByte(2); @@ -465,21 +480,22 @@ Reads the **Byte** value from this **MessageParcel** object. writeShort(val: number): boolean -Writes a **Short int** value to this **MessageParcel** object. +Writes a Short int value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Short int** value to write. | + | val | number | Yes| Short int value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeShort(8); @@ -491,16 +507,17 @@ Writes a **Short int** value to this **MessageParcel** object. readShort(): number -Reads the **Short int** value from this **MessageParcel** object. +Reads the Short int value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Short int** value read. | + | number | Short int value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeShort(8); @@ -514,21 +531,22 @@ Reads the **Short int** value from this **MessageParcel** object. writeInt(val: number): boolean -Writes an **Int** value to this **MessageParcel** object. +Writes an Int value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Int** value to write. | + | val | number | Yes| Int value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeInt(10); @@ -540,16 +558,17 @@ Writes an **Int** value to this **MessageParcel** object. readInt(): number -Reads the **Int** value from this **MessageParcel** object. +Reads the Int value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Int** value read. | + | number | Int value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeInt(10); @@ -563,21 +582,22 @@ Reads the **Int** value from this **MessageParcel** object. writeLong(val: number): boolean -Writes a **Long int** value to this **MessageParcel** object. +Writes a Long int value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Long int** value to write. | + | val | number | Yes| Long int value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeLong(10000); @@ -589,16 +609,17 @@ Writes a **Long int** value to this **MessageParcel** object. readLong(): number -Reads the **Long int** value from this **MessageParcel** object. +Reads the Long int value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Long int** value read. | + | number | Long int value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeLong(10000); @@ -612,21 +633,22 @@ Reads the **Long int** value from this **MessageParcel** object. writeFloat(val: number): boolean -Writes a **Float** value to this **MessageParcel** object. +Writes a Float value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Float** value to write. | + | val | number | Yes| Float value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeFloat(1.2); @@ -638,16 +660,17 @@ Writes a **Float** value to this **MessageParcel** object. readFloat(): number -Reads the **Float** value from this **MessageParcel** object. +Reads the Float value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Float** value read. | + | number | Float value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeFloat(1.2); @@ -661,21 +684,22 @@ Reads the **Float** value from this **MessageParcel** object. writeDouble(val: number): boolean -Writes a **Double** value to this **MessageParcel** object. +Writes a Double value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Double** value to write. | + | val | number | Yes| Double value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeDouble(10.2); @@ -687,16 +711,17 @@ Writes a **Double** value to this **MessageParcel** object. readDouble(): number -Reads the **Double** value from this **MessageParcel** object. +Reads the Double value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Double** value read. | + | number | Double value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeDouble(10.2); @@ -710,21 +735,22 @@ Reads the **Double** value from this **MessageParcel** object. writeBoolean(val: boolean): boolean -Writes a **Boolean** value to this **MessageParcel** object. +Writes a Boolean value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | boolean | Yes | **Boolean** value to write. | + | val | boolean | Yes| Boolean value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeBoolean(false); @@ -736,16 +762,17 @@ Writes a **Boolean** value to this **MessageParcel** object. readBoolean(): boolean -Reads the **Boolean** value from this **MessageParcel** object. +Reads the Boolean value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | **Boolean** value read. | + | boolean | Boolean value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeBoolean(false); @@ -759,21 +786,22 @@ Reads the **Boolean** value from this **MessageParcel** object. writeChar(val: number): boolean -Writes a **Char** value to this **MessageParcel** object. +Writes a Char value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | number | Yes | **Char** value to write. | + | val | number | Yes| Char value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeChar('a'); @@ -785,16 +813,17 @@ Writes a **Char** value to this **MessageParcel** object. readChar(): number -Reads the **Char** value from this **MessageParcel** object. +Reads the Char value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | **Char** value read. | + | number | Char value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeChar('a'); @@ -808,21 +837,22 @@ Reads the **Char** value from this **MessageParcel** object. writeString(val: string): boolean -Writes a **String** value to this **MessageParcel** object. +Writes a String value to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | string | Yes | **String** value to write. | + | val | string | Yes| String value to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeString('abc'); @@ -834,16 +864,17 @@ Writes a **String** value to this **MessageParcel** object. readString(): string -Reads the **String** value from this **MessageParcel** object. +Reads the String value from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | **String** value read. | + | string | String value read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeString('abc'); @@ -859,19 +890,20 @@ writeSequenceable(val: Sequenceable): boolean Writes a sequenceable object to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | [Sequenceable](#sequenceable) | Yes | Sequenceable object to write. | + | val | [Sequenceable](#sequenceable) | Yes| Sequenceable object to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -900,21 +932,22 @@ Writes a sequenceable object to this **MessageParcel** object. readSequenceable(dataIn: Sequenceable) : boolean -Reads member variables from the **MessageParcel** instance. +Reads member variables from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | [Sequenceable](#sequenceable) | Yes | Object that reads member variables from the **MessageParcel** instance. | + | dataIn | [Sequenceable](#sequenceable) | Yes| Object that reads member variables from the **MessageParcel** object.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -946,21 +979,22 @@ Reads member variables from the **MessageParcel** instance. writeByteArray(byteArray: number[]): boolean -Writes a **ByteArray** to this **MessageParcel** object. +Writes a ByteArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | byteArray | number[] | Yes | **ByteArray** to write. | + | byteArray | number[] | Yes| ByteArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); @@ -973,16 +1007,17 @@ Writes a **ByteArray** to this **MessageParcel** object. readByteArray(dataIn: number[]) : void -Reads the **ByteArray** from this **MessageParcel** object. +Reads the ByteArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **ByteArray** to read. | + | dataIn | number[] | Yes| ByteArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); @@ -997,16 +1032,17 @@ Reads the **ByteArray** from this **MessageParcel** object. readByteArray(): number[] -Reads the **ByteArray** from this **MessageParcel** object. +Reads the ByteArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **ByteArray** read. | + | number[] | ByteArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); @@ -1021,21 +1057,22 @@ Reads the **ByteArray** from this **MessageParcel** object. writeShortArray(shortArray: number[]): boolean -Writes a **ShortArray** to this **MessageParcel** object. +Writes a ShortArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | shortArray | number[] | Yes | **ShortArray** to write. | + | shortArray | number[] | Yes| ShortArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); @@ -1047,16 +1084,17 @@ Writes a **ShortArray** to this **MessageParcel** object. readShortArray(dataIn: number[]) : void -Reads the **ShortArray** from this **MessageParcel** object. +Reads a ShortArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **ShortArray** to read. | + | dataIn | number[] | Yes| ShortArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); @@ -1070,16 +1108,17 @@ Reads the **ShortArray** from this **MessageParcel** object. readShortArray(): number[] -Reads the **ShortArray** from this **MessageParcel** object. +Reads the ShortArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **ShortArray** read. | + | number[] | ShortArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); @@ -1093,21 +1132,22 @@ Reads the **ShortArray** from this **MessageParcel** object. writeIntArray(intArray: number[]): boolean -Writes an **IntArray** to this **MessageParcel** object. +Writes an IntArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | intArray | number[] | Yes | **IntArray** to write. | + | intArray | number[] | Yes| IntArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); @@ -1119,16 +1159,17 @@ Writes an **IntArray** to this **MessageParcel** object. readIntArray(dataIn: number[]) : void -Reads the **IntArray** from this **MessageParcel** object. +Reads an IntArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **IntArray** to read. | + | dataIn | number[] | Yes| IntArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); @@ -1142,16 +1183,17 @@ Reads the **IntArray** from this **MessageParcel** object. readIntArray(): number[] -Reads the **IntArray** from this **MessageParcel** object. +Reads the IntArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **IntArray** read. | + | number[] | IntArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); @@ -1165,21 +1207,22 @@ Reads the **IntArray** from this **MessageParcel** object. writeLongArray(longArray: number[]): boolean -Writes a **LongArray** to this **MessageParcel** object. +Writes a LongArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | longArray | number[] | Yes | **LongArray** to write. | + | longArray | number[] | Yes| LongArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); @@ -1191,16 +1234,17 @@ Writes a **LongArray** to this **MessageParcel** object. readLongArray(dataIn: number[]) : void -Reads the **LongArray** from this **MessageParcel** object. +Reads a LongArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **LongArray** to read. | + | dataIn | number[] | Yes| LongArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); @@ -1214,16 +1258,17 @@ Reads the **LongArray** from this **MessageParcel** object. readLongArray(): number[] -Reads the **LongArray** from this **MessageParcel** object. +Reads the LongArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **LongArray** read. | + | number[] | LongArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); @@ -1237,21 +1282,22 @@ Reads the **LongArray** from this **MessageParcel** object. writeFloatArray(floatArray: number[]): boolean -Writes a **FloatArray** to this **MessageParcel** object. +Writes a FloatArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | floatArray | number[] | Yes | **FloatArray** to write. | + | floatArray | number[] | Yes| FloatArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1263,16 +1309,18 @@ Writes a **FloatArray** to this **MessageParcel** object. readFloatArray(dataIn: number[]) : void -Reads the **FloatArray** from this **MessageParcel** object. +Reads a FloatArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **FloatArray** to read. | + | dataIn | number[] | Yes| FloatArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1286,16 +1334,17 @@ Reads the **FloatArray** from this **MessageParcel** object. readFloatArray(): number[] -Reads the **FloatArray** from this **MessageParcel** object. +Reads the FloatArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **FloatArray** read. | + | number[] | FloatArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1309,21 +1358,22 @@ Reads the **FloatArray** from this **MessageParcel** object. writeDoubleArray(doubleArray: number[]): boolean -Writes a **DoubleArray** to this **MessageParcel** object. +Writes a DoubleArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | doubleArray | number[] | Yes | **DoubleArray** to write. | + | doubleArray | number[] | Yes| DoubleArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -1335,16 +1385,17 @@ Writes a **DoubleArray** to this **MessageParcel** object. readDoubleArray(dataIn: number[]) : void -Reads the **DoubleArray** from this **MessageParcel** object. +Reads a DoubleArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes | **DoubleArray** to read. | + | dataIn | number[] | Yes| DoubleArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -1358,16 +1409,17 @@ Reads the **DoubleArray** from this **MessageParcel** object. readDoubleArray(): number[] -Reads the **DoubleArray** from this **MessageParcel** object. +Reads the DoubleArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | **DoubleArray** read. | + | number[] | DoubleArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -1381,21 +1433,22 @@ Reads the **DoubleArray** from this **MessageParcel** object. writeBooleanArray(booleanArray: boolean[]): boolean -Writes a **BooleanArray** to this **MessageParcel** object. +Writes a BooleanArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | booleanArray | boolean[] | Yes | **BooleanArray** to write. | + | booleanArray | boolean[] | Yes| BooleanArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); @@ -1407,16 +1460,17 @@ Writes a **BooleanArray** to this **MessageParcel** object. readBooleanArray(dataIn: boolean[]) : void -Reads the **BooleanArray** from this **MessageParcel** object. +Reads a BooleanArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | boolean[] | Yes | **BooleanArray** to read. | + | dataIn | boolean[] | Yes| BooleanArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); @@ -1430,15 +1484,16 @@ Reads the **BooleanArray** from this **MessageParcel** object. readBooleanArray(): boolean[] -Reads the **BooleanArray** from this **MessageParcel** object. +Reads the BooleanArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean[] | **BooleanArray** read. | + | boolean[] | BooleanArray read.| + - ``` let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); @@ -1452,21 +1507,22 @@ Reads the **BooleanArray** from this **MessageParcel** object. writeCharArray(charArray: number[]): boolean -Writes a **CharArray** to this **MessageParcel** object. +Writes a CharArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | charArray | number[] | Yes | **CharArray** to write. | + | charArray | number[] | Yes| CharArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeCharArray(['a', 'b', 'c']); @@ -1476,18 +1532,19 @@ Writes a **CharArray** to this **MessageParcel** object. ### readCharArray -readCharArray(dataIn: boolean[]) : void +readCharArray(dataIn: number[]) : void -Reads the **CharArray** from this **MessageParcel** object. +Reads a CharArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | boolean[] | Yes | **CharArray** to read. | + | dataIn | number[] | Yes| CharArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeCharArray(['a', 'b', 'c']); @@ -1499,18 +1556,19 @@ Reads the **CharArray** from this **MessageParcel** object. ### readCharArray -readCharArray(): boolean[] +readCharArray(): number[] -Reads the **CharArray** from this **MessageParcel** object. +Reads the CharArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean[] | **CharArray** read. | + | number[] | CharArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeCharArray(['a', 'b', 'c']); @@ -1524,21 +1582,22 @@ Reads the **CharArray** from this **MessageParcel** object. writeStringArray(stringArray: string[]): boolean -Writes a **StringArray** to this **MessageParcel** object. +Writes a StringArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | stringArray | string[] | Yes | **StringArray** to write. | + | stringArray | string[] | Yes| StringArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); @@ -1550,16 +1609,17 @@ Writes a **StringArray** to this **MessageParcel** object. readStringArray(dataIn: string[]) : void -Reads the **StringArray** from this **MessageParcel** object. +Reads a StringArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | string[] | Yes | **StringArray** to read. | + | dataIn | string[] | Yes| StringArray to read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); @@ -1573,16 +1633,17 @@ Reads the **StringArray** from this **MessageParcel** object. readStringArray(): string[] -Reads the **StringArray** from this **MessageParcel** object. +Reads the StringArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string[] | **StringArray** read. | + | string[] | StringArray read.| - Example - + ``` let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); @@ -1598,9 +1659,10 @@ writeNoException(): void Writes information to this **MessageParcel** object indicating that no exception occurred. +**System capability**: SystemCapability.Communication.IPC.Core - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -1626,9 +1688,10 @@ readException(): void Reads the exception information from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -1645,8 +1708,8 @@ Reads the exception information from this **MessageParcel** object. } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -1678,21 +1741,22 @@ Reads the exception information from this **MessageParcel** object. writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean -Writes a **SequenceableArray** to this **MessageParcel** object. +Writes a SequenceableArray to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes | **SequenceableArray** to write. | + | sequenceableArray | Sequenceable[] | Yes| SequenceableArray to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -1724,16 +1788,17 @@ Writes a **SequenceableArray** to this **MessageParcel** object. readSequenceableArray(sequenceableArray: Sequenceable[]): void -Reads the specified **SequenceableArray** from this **MessageParcel** object. +Reads a SequenceableArray from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes | **SequenceableArray** to read. | + | sequenceableArray | Sequenceable[] | Yes| SequenceableArray to read.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -1769,19 +1834,20 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean Writes an array of **IRemoteObject** objects to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write. | + | objectArray | IRemoteObject[] | Yes| Array of **IRemoteObject** objects to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the **IRemoteObject** array is successfully written to the **MessageParcel**; returns **false** if the **IRemoteObject** array is null or fails to be written to the **MessageParcel**. | + | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -1800,16 +1866,17 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. readRemoteObjectArray(objects: IRemoteObject[]): void -Reads the specified **IRemoteObject** array from this **MessageParcel** object. +Reads an **IRemoteObject** array from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read. | + | objects | IRemoteObject[] | Yes| **IRemoteObject** array to read.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -1829,16 +1896,17 @@ Reads the specified **IRemoteObject** array from this **MessageParcel** object. readRemoteObjectArray(): IRemoteObject[] -Reads **IRemoteObject** objects from this **MessageParcel** object. +Reads the **IRemoteObject** array from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | IRemoteObject[] | An array of **IRemoteObject** objects obtained. | + | IRemoteObject[] | **IRemoteObject** object array obtained.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -1859,16 +1927,17 @@ Reads **IRemoteObject** objects from this **MessageParcel** object. static closeFileDescriptor(fd: number): void -Closes the specified file descriptor. +Closes a file descriptor. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | fd | number | Yes | File descriptor to close. | + | fd | number | Yes| File descriptor to close.| - Example - + ``` import fileio from '@ohos.fileio'; let filePath = "path/to/file"; @@ -1881,21 +1950,22 @@ Closes the specified file descriptor. static dupFileDescriptor(fd: number) :number -Duplicates the specified file descriptor. +Duplicates a file descriptor. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | fd | number | Yes | File descriptor to duplicate. | + | fd | number | Yes| File descriptor to duplicate.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | New file descriptor. | + | number | New file descriptor.| - Example - + ``` import fileio from '@ohos.fileio'; let filePath = "path/to/file"; @@ -1910,14 +1980,15 @@ containFileDescriptors(): boolean Checks whether this **MessageParcel** object contains a file descriptor. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise. | + | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| - Example - + ``` import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); @@ -1937,19 +2008,20 @@ writeFileDescriptor(fd: number): boolean Writes a file descriptor to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | fd | number | Yes | File descriptor to write. | + | fd | number | Yes| File descriptor to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); @@ -1964,16 +2036,17 @@ Writes a file descriptor to this **MessageParcel** object. readFileDescriptor(): number -Reads a file descriptor from this **MessageParcel** object. +Reads the file descriptor from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | File descriptor obtained. | + | number | File descriptor read.| - Example - + ``` import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); @@ -1991,19 +2064,20 @@ writeAshmem(ashmem: Ashmem): boolean Writes an anonymous shared object to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes | Anonymous shared object to write. | + | ashmem | Ashmem | Yes| Anonymous shared object to write.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let parcel = new rpc.MessageParcel(); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); @@ -2018,14 +2092,15 @@ readAshmem(): Ashmem Reads the anonymous shared object from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Ashmem | Anonymous share object obtained. | + | Ashmem | Anonymous share object obtained.| - Example - + ``` let parcel = new rpc.MessageParcel(); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); @@ -2042,14 +2117,15 @@ getRawDataCapacity(): number Obtains the maximum amount of raw data that can be held by this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object. | + | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| - Example - + ``` let parcel = new rpc.MessageParcel(); let result = parcel.getRawDataCapacity(); @@ -2063,20 +2139,21 @@ writeRawData(rawData: number[], size: number): boolean Writes raw data to this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | rawData | number[] | Yes | Raw data to write. | - | size | number | Yes | Size of the raw data, in bytes. | + | rawData | number[] | Yes| Raw data to write.| + | size | number | Yes| Size of the raw data, in bytes.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let parcel = new rpc.MessageParcel(); let arr = new Int8Array([1, 2, 3, 4, 5]); @@ -2091,19 +2168,20 @@ readRawData(size: number): number[] Reads raw data from this **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | size | number | Yes | Size of the raw data to read. | + | size | number | Yes| Size of the raw data to read.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | Raw data obtained, in bytes. | + | number[] | Raw data obtained, in bytes.| - Example - + ``` let parcel = new rpc.MessageParcel(); let arr = new Int8Array([1, 2, 3, 4, 5]); @@ -2113,90 +2191,31 @@ Reads raw data from this **MessageParcel** object. console.log("RpcTest: parcel read raw data result is : " + result); ``` - -### getDataVersion8+ - -getDataVersion(): number - -Obtains the data format version from this **MessageParcel** object. - - -- Return values - | Type | Description | - | -------- | -------- | - | number | Data format version obtained. | - -- Example - - ``` - let parcel = new rpc.MessageParcel(); - let version = parcel.getDataVersion(); - console.log("RpcTest: parcel get data version is : " + version); - ``` - - -### updateDataVersion8+ - -updateDataVersion(proxy: IRemoteObject): void - -Updates the data format version of the **IRemoteObject** to this **MessageParcel** object. - - -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | proxy | IRemoteObject | Yes | Remote object that uses this **MessageParcel** object to send the request. | - -- Example - - ``` - import FA from "@ohos.ability.featureAbility"; - let proxy; - let connect = { - onConnect: function(elementName, remoteProxy) { - console.log("RpcClient: js onConnect called."); - proxy = remoteProxy; - }, - onDisconnect: function(elementName) { - console.log("RpcClient: onDisconnect"); - }, - onFailed: function() { - console.log("RpcClient: onFailed"); - } - }; - let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", - }; - FA.connectAbility(want, connect); - let parcel = new rpc.MessageParcel(); - parcel.updateDataVersion(proxy); - ``` - - ## Sequenceable -Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during inter-process communication (IPC). +Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during IPC. ### marshalling marshalling(dataOut: MessageParcel): boolean -Marshals this sequenceable object into a **MessageParcel** object. +Marshals the sequenceable object into a **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataOut | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled. | + | dataOut | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object to which the sequenceable object is to be marshaled.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -2230,18 +2249,20 @@ unmarshalling(dataIn: MessageParcel) : boolean Unmarshals this sequenceable object from a **MessageParcel** object. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | dataIn | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object in which the sequenceable object has been marshaled. | + | dataIn | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object in which the sequenceable object is to be unmarshaled.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class MySequenceable { constructor(num, string) { @@ -2280,13 +2301,15 @@ asObject(): IRemoteObject Obtains a proxy or remote object. This method must be implemented by its derived classes. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | [IRemoteObject](#iremoteobject) | Returns the [RemoteObject](#ashmem8) if the caller is a [RemoteObject](#ashmem8); returns the [IRemoteObject](#iremoteobject), that is, the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object. | + | [IRemoteObject](#iremoteobject) | Returns the [RemoteObject](#ashmem8) if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| - Example - + ``` class TestAbility extends rpc.RemoteObject { asObject() { @@ -2296,7 +2319,7 @@ Obtains a proxy or remote object. This method must be implemented by its derived ``` - Example - + ``` class TestProxy { constructor(remote) { @@ -2311,7 +2334,7 @@ Obtains a proxy or remote object. This method must be implemented by its derived ## DeathRecipient -Subscribes to death notifications of a remote object. When the remote object is dead, the local end will receive a notification and [onRemoteDied](#onremotedied) will be called. A remote object is dead when the process holding the object is terminated or the device of the remote object is shut down or restarted. If the local and remote objects belong to different devices, the remote object is dead when the device holding the remote object is detached from the network. +Subscribes to death notifications of a remote object. When the remote object is dead, the local end will receive a notification and **[onRemoteDied](#onremotedied)** will be called. A remote object is dead when the process holding the object is terminated or the device of the remote object is shut down or restarted. If the local and remote objects belong to different devices, the remote object is dead when the device holding the remote object is detached from the network. ### onRemoteDied @@ -2320,8 +2343,10 @@ onRemoteDied(): void Called to perform subsequent operations when a death notification of the remote object is received. +**System capability**: SystemCapability.Communication.IPC.Core + - Example - + ``` class MyDeathRecipient { onRemoteDied() { @@ -2335,17 +2360,19 @@ Called to perform subsequent operations when a death notification of the remote Defines the response to the request. - | Parameters | Value | Description | +**System capability**: SystemCapability.Communication.IPC.Core + + | Parameter| Value| Description| | -------- | -------- | -------- | -| errCode | number | Error code. | -| code | number | Message code. | -| data | MessageParcel | **MessageParcel** object sent to the peer process. | -| reply | MessageParcel | **MessageParcel** object returned by the peer process. | +| errCode | number | Error Code| +| code | number | Message code.| +| data | MessageParcel | **MessageParcel** object sent to the remote process.| +| reply | MessageParcel | **MessageParcel** object returned by the remote process.| ## IRemoteObject -Provides methods to query or obtain interface descriptors, add or delete death notifications, dump object status to specific files, and send messages. +Provides methods to query of obtain interface descriptors, add or delete death notifications, dump object status to specific files, and send messages. ### queryLocalInterface @@ -2354,53 +2381,59 @@ queryLocalInterface(descriptor: string): IRemoteBroker Obtains the interface. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | descriptor | string | Yes | Interface descriptor. | + | descriptor | string | Yes| Interface descriptor.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface descriptor. | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface descriptor.| ### sendRequest -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<number>7 +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned. 7
Promise used to return the **sendRequestResult** instance. 8+ | + | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | ### sendRequest8+ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| ### addDeathrecipient @@ -2409,16 +2442,18 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | - | flags | number | Yes | Flag of the death notification. | + | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| + | flags | number | Yes| Flag of the death notification.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise. | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| ### removeDeathRecipient @@ -2427,71 +2462,91 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean Removes the callback used to receive death notifications of the remote object. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | - | flags | number | Yes | Flag of the death notification. | + | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| + | flags | number | Yes| Flag of the death notification.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise. | + | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| ### getInterfaceDescriptor getInterfaceDescriptor(): string -Obtains the interface descriptor of the object. The interface descriptor is a string. +Obtains the interface descriptor of this object. The interface descriptor is a string. + +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | Interface descriptor obtained. | + | string | Interface descriptor obtained.| ### isObjectDead isObjectDead(): boolean -Checks whether the current object is dead. +Checks whether this object is dead. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the object is dead; returns **false** otherwise. | + | boolean | Returns **true** if the object is dead; returns **false** otherwise.| ## RemoteProxy Provides methods to implement **IRemoteObject**. +**System capability**: SystemCapability.Communication.IPC.Core + +| Parameter | Value | Description | +| --------------------- | ----------------------- | --------------------------------- | +| PING_TRANSACTION | 1599098439 (0x5f504e47) | Internal instruction code used to test whether the IPC service is normal.| +| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | Internal instruction code used to obtain the internal status of the binder.| +| INTERFACE_TRANSACTION | 1598968902 (0x5f4e5446) | Internal instruction code used to obtain the remote interface descriptor. | +| MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. | +| MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. | + + + ### sendRequest -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<number>7 +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned. 7
Promise used to return the **sendRequestResult** instance. 8+ | + | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | + +- Example:7 -- Example7 - ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2508,8 +2563,8 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -2535,8 +2590,8 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro }); ``` -- Example8+ - +- Example:8+ + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2553,8 +2608,8 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -2586,20 +2641,21 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2616,8 +2672,8 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; function sendRequestCallback(result) { if (result.errCode === 0) { @@ -2648,19 +2704,20 @@ queryLocalInterface(interface: string): IRemoteBroker Obtains the **LocalInterface** object of an interface descriptor. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | interface | string | Yes | Interface descriptor. | + | interface | string | Yes| Interface descriptor.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface. | + | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2677,8 +2734,8 @@ Obtains the **LocalInterface** object of an interface descriptor. } }; let want = { - "bundleName":"com.huawei.server", - "abilityName":"com.huawei.server.MainAbility", + "bundleName":"com.ohos.server", + "abilityName":"com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let broker = proxy.queryLocalInterface("testObject"); @@ -2692,20 +2749,21 @@ addDeathRecipient(recipient : DeathRecipient, flags : number): boolean Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | - | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**. | + | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| + | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise. | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2722,8 +2780,8 @@ Adds a callback for receiving the death notifications of the remote object, incl } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -2742,20 +2800,21 @@ removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean Removes the callback used to receive death notifications of the remote object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | - | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**. | + | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| + | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise. | + | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2772,8 +2831,8 @@ Removes the callback used to receive death notifications of the remote object. } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -2793,14 +2852,15 @@ getInterfaceDescriptor(): string Obtains the interface descriptor of this proxy object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | Interface descriptor obtained. | + | string | Interface descriptor obtained.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2817,8 +2877,8 @@ Obtains the interface descriptor of this proxy object. } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let descriptor = proxy.getInterfaceDescriptor(); @@ -2832,14 +2892,15 @@ isObjectDead(): boolean Checks whether the **RemoteObject** is dead. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise. | + | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| - Example - + ``` import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2856,8 +2917,8 @@ Checks whether the **RemoteObject** is dead. } }; let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); let isDead = proxy.isObjectDead(); @@ -2865,99 +2926,61 @@ Checks whether the **RemoteObject** is dead. ``` -### setDataVersion8+ - -setDataVersion(dataVersion: number): boolean - -Sets the data format version to this **RemoteProxy** object. - - -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | dataVersion | number | Yes | Data format version to set. | - -- Return values - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | - -- Example - - ``` - import FA from "@ohos.ability.featureAbility"; - let proxy; - let connect = { - onConnect: function(elementName, remoteProxy) { - console.log("RpcClient: js onConnect called."); - proxy = remoteProxy; - }, - onDisconnect: function(elementName) { - console.log("RpcClient: onDisconnect"); - }, - onFailed: function() { - console.log("RpcClient: onFailed"); - } - }; - let want = { - "bundleName": "com.huawei.server", - "abilityName": "com.huawei.server.MainAbility", - }; - FA.connectAbility(want, connect); - let result = proxy.setDataVersion(1); - console.log("RpcClient: set Data Version is " + result); - ``` - - ## MessageOption Provides common message options (flag and wait time). The flag is used to construct the specified **MessageOption** object. +**System capability**: SystemCapability.Communication.IPC.Core - | Parameters | Value | Description | + | Parameter| Value| Description| | -------- | -------- | -------- | -| TF_SYNC | 0 | Synchronous call. | -| TF_ASYNC | 1 | Asynchronous call. | -| TF_ACCEPT_FDS | 0x10 | Indication to the [sendRequest](#sendrequest8) API for returning the file descriptor. | -| TF_WAIT_TIME | 8 | Wait time, in seconds. | +| TF_SYNC | 0 | Synchronous call.| +| TF_ASYNC | 1 | Asynchronous call.| +| TF_ACCEPT_FDS | 0x10 | Indication to the [sendRequest](#sendrequest8) API for returning the file descriptor.| +| TF_WAIT_TIME | 8 | Time to wait, in seconds.| ### constructor constructor(syncFlags?: number, waitTime = TF_WAIT_TIME) -A constructor used to create a **MessageOption** instance. +A constructor used to create a **MessageOption** object. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | syncFlags | number | No | Specifies whether the **SendRequest** is called synchronously (default) or asynchronously. | - | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**. | + | syncFlags | number | No| Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| + | waitTime | number | No| Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| ### getFlags getFlags(): number -Obtains the **SendRequest** call flag, which can be synchronous or asynchronous. +Obtains the call flag, which can be synchronous or asynchronous. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Whether the **SendRequest** is called synchronously or asynchronously. | + | number | Call mode obtained.| ### setFlags setFlags(flags: number): void -Sets the **SendRequest** call flag, which can be synchronous or asynchronous. +Sets the call flag, which can be synchronous or asynchronous. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | flags | number | Yes | Call flag, which can be synchronous or asynchronous. | + | flags | number | Yes| Call flag to set.| ### getWaitTime @@ -2966,10 +2989,12 @@ getWaitTime(): number Obtains the maximum wait time for this RPC call. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | number | Maximum wait time obtained. | + | number | Maximum wait time obtained.| ### setWaitTime @@ -2978,15 +3003,17 @@ setWaitTime(waitTime: number): void Sets the maximum wait time for this RPC call. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | waitTime | number | Yes | Maximum wait time to set. | + | waitTime | number | Yes| Maximum wait time to set.| ## IPCSkeleton -Obtains IPC context information, including the UID and PID, local and peer device IDs, and whether the method is invoked on the same device. +Obtains IPC context information, including the UID and PID, local and remote device IDs, and whether the method is invoked on the same device. ### getContextObject @@ -2995,14 +3022,15 @@ static getContextObject(): IRemoteObject Obtains the system capability manager. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | [IRemoteObject](#iremoteobject) | System capability manager. | + | [IRemoteObject](#iremoteobject) | System capability manager obtained.| - Example - + ``` let samgr = rpc.IPCSkeleton.getContextObject(); console.log("RpcServer: getContextObject result: " + samgr); @@ -3015,14 +3043,15 @@ static getCallingPid(): number Obtains the PID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | PID of the caller. | + | number | PID of the caller.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3040,14 +3069,15 @@ static getCallingUid(): number Obtains the UID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | UID of the caller. | + | number | UID of the caller.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3058,6 +3088,32 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob } ``` +### getCallingTokenId + +static getCallingTokenId(): number; + +Obtains the caller's token ID, which is used to verify the caller identity. + +**System capability**: SystemCapability.Communication.IPC.Core + +Return value + + | Type | Description | + | ------ | --------------------- | + | number | Token ID of the caller obtained.| + +Example + + ``` + class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); + console.log("RpcServer: getCallingTokenId result: " + callerTokenId); + return true; + } + } + ``` + ### getCalligDeviceID @@ -3065,14 +3121,15 @@ static getCallingDeviceID(): string Obtains the ID of the device hosting the caller's process. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | Device ID obtained. | + | string | Device ID obtained.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3090,14 +3147,15 @@ static getLocalDeviceID(): string Obtains the local device ID. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | Local device ID obtained. | + | string | Local device ID obtained.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3113,16 +3171,17 @@ Obtains the local device ID. static isLocalCalling(): boolean -Checks whether the peer process is a process of the local device. +Checks whether the remote process is a process of the local device. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the local and peer processes are on the same device; returns false otherwise. | + | boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3140,19 +3199,21 @@ static flushCommands(object : IRemoteObject): number Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy**. | + | object | [IRemoteObject](#iremoteobject) | Yes| **RemoteProxy** specified. | -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or the operation fails. | + | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| - Example - + ``` let remoteObject = new rpc.RemoteObject("aaa", 3); let ret = rpc.IPCSkeleton.flushCommands(remoteObject); @@ -3166,14 +3227,15 @@ static resetCallingIdentity(): string Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | string | String containing the UID and PID of the remote user. | + | string | String containing the UID and PID of the remote user.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3191,18 +3253,20 @@ static setCallingIdentity(identity : string): boolean Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**. | + | identity | string | Yes| String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { @@ -3229,38 +3293,42 @@ Provides methods to implement **RemoteObject**. The service provider must inheri constructor(descriptor: string) -A constructor used to create a **RemoteObject** instance. +A constructor used to create a **RemoteObject** object. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | descriptor | string | Yes | Interface descriptor. | + | descriptor | string | Yes| Interface descriptor.| ### sendRequest -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<number>7 +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned. 7
Promise used to return the **sendRequestResult** instance. 8+ | + | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | - Example7 - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3293,7 +3361,7 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro - Example8+ - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3330,20 +3398,22 @@ Sends a **MessageParcel** message to the peer process in synchronous or asynchro sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | AsyncCallback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | AsyncCallback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3379,28 +3449,30 @@ onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, optio Provides a response to **sendRequest()**. The server processes the request and returns a response in this function. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | code | number | Yes | Service request code sent by the peer end. | - | data | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object that holds the parameters called by the client. | - | reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel** object carrying the result. | - | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | + | code | number | Yes| Service request code sent by the remote end.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that holds the parameters called by the client.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| + | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - + onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); @@ -3418,16 +3490,18 @@ Provides a response to **sendRequest()**. The server processes the request and r getCallingUid(): number -Obtains the UID of the peer process. +Obtains the UID of the remote process. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | number | UID of the peer process obtained. | + | number | UID of the remote process obtained.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3443,16 +3517,18 @@ Obtains the UID of the peer process. getCallingPid(): number -Obtains the PID of the peer process. +Obtains the PID of the remote process. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | number | PID of the peer process obtained. | + | number | PID of the remote process obtained.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3466,23 +3542,25 @@ Obtains the PID of the peer process. ### queryLocalInterface -queryLocalInterface(descriptor: descriptor): IRemoteBroker +queryLocalInterface(descriptor: string): IRemoteBroker Checks whether the remote object corresponding to the specified interface descriptor exists. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | descriptor | descriptor | Yes | Interface descriptor. | + | descriptor | string | Yes| Interface descriptor.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise. | + | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3500,14 +3578,16 @@ getInterfaceDescriptor(): string Obtains the interface descriptor. -- Return values - | Type | Description | +**System capability**: SystemCapability.Communication.IPC.Core + +- Return value + | Type| Description| | -------- | -------- | - | string | Interface descriptor obtained. | + | string | Interface descriptor obtained.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3526,15 +3606,17 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void Binds an interface descriptor to an **IRemoteBroker** object. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | - | descriptor | string | Yes | Interface descriptor. | + | localInterface | IRemoteBroker | Yes| **IRemoteBroker** object.| + | descriptor | string | Yes| Interface descriptor.| - Example - + ``` class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { @@ -3550,36 +3632,40 @@ Binds an interface descriptor to an **IRemoteBroker** object. Provides methods related to anonymous shared memory objects, including creating, closing, mapping, and unmapping an **Ashmem** object, reading data from and writing data to an **Ashmem** object, obtaining the **Ashmem** size, and setting **Ashmem** protection. -The following table describes the protection types of the mapped memory. +The table below describes the protection types of the mapped memory. + +**System capability**: SystemCapability.Communication.IPC.Core - | Name | Value | Description | + | Name| Value| Description| | -------- | -------- | -------- | -| PROT_EXEC | 4 | The mapped memory is executable. | -| PROT_NONE | 0 | The mapped memory is inaccessible. | -| PROT_READ | 1 | The mapped memory is readable. | -| PROT_WRITE | 2 | The mapped memory is writeable. | +| PROT_EXEC | 4 | The mapped memory is executable.| +| PROT_NONE | 0 | The mapped memory is inaccessible.| +| PROT_READ | 1 | The mapped memory is readable.| +| PROT_WRITE | 2 | The mapped memory is writeable.| -### createAshmem +### createAshmem8+ static createAshmem(name: string, size: number): Ashmem Creates an **Ashmem** object with the specified name and size. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the **Ashmem** object to create. | - | size | number | Yes | Size (in bytes) of the **Ashmem** object to create. | + | name | string | Yes| Name of the **Ashmem** object to create.| + | size | number | Yes| Size (in bytes) of the **Ashmem** object to create.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Ashmem | Returns the **Ashmem** object if it is created successfully; returns **null** otherwise. | + | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let size = ashmem.getAshmemSize(); @@ -3587,25 +3673,27 @@ Creates an **Ashmem** object with the specified name and size. ``` -### createAshmemFromExisting +### createAshmemFromExisting8+ static createAshmemFromExisting(ashmem: Ashmem): Ashmem -Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region. +Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. + +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes | Existing **Ashmem** object. | + | ashmem | Ashmem | Yes| Existing **Ashmem** object.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | Ashmem | **Ashmem** object created. | + | Ashmem | **Ashmem** object created.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem); @@ -3614,50 +3702,53 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing ``` -### closeAshmem +### closeAshmem8+ closeAshmem(): void Closes this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); ashmem.closeAshmem(); ``` -### unmapAshmem +### unmapAshmem8+ unmapAshmem(): void Deletes the mappings for the specified address range of this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); ashmem.unmapAshmem(); ``` -### getAshmemSize +### getAshmemSize8+ getAshmemSize(): number Obtains the memory size of this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number | Memory size obtained. | + | number | **Ashmem** size obtained.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let size = ashmem.getAshmemSize(); @@ -3665,25 +3756,26 @@ Obtains the memory size of this **Ashmem** object. ``` -### mapAshmem +### mapAshmem8+ mapAshmem(mapType: number): boolean Creates the shared file mapping on the virtual address space of this process. The size of the mapping region is specified by this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped. | + | mapType | number | Yes| Protection level of the memory region to which the shared file is mapped.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapReadAndWrite = ashmem.mapAshmem(rpc.Ashmem.PROT_READ | rpc.Ashmem.PROT_WRITE); @@ -3691,20 +3783,21 @@ Creates the shared file mapping on the virtual address space of this process. Th ``` -### mapReadAndWriteAshmem +### mapReadAndWriteAshmem8+ mapReadAndWriteAshmem(): boolean Maps the shared file to the readable and writable virtual address space of the process. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); @@ -3712,20 +3805,21 @@ Maps the shared file to the readable and writable virtual address space of the p ``` -### mapReadOnlyAshmem +### mapReadOnlyAshmem8+ mapReadOnlyAshmem(): boolean Maps the shared file to the read-only virtual address space of the process. +**System capability**: SystemCapability.Communication.IPC.Core -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadOnlyAshmem(); @@ -3733,25 +3827,26 @@ Maps the shared file to the read-only virtual address space of the process. ``` -### setProtection +### setProtection8+ setProtection(protectionType: number): boolean Sets the protection level of the memory region to which the shared file is mapped. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | protectionType | number | Yes | Protection type to set. | + | protectionType | number | Yes| Protection type to set.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let result = ashmem.setProtection(rpc.Ashmem.PROT_READ); @@ -3759,27 +3854,28 @@ Sets the protection level of the memory region to which the shared file is mappe ``` -### writeToAshmem +### writeToAshmem8+ writeToAshmem(buf: number[], size: number, offset: number): boolean Writes data to the shared file associated with this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | buf | number[] | Yes | Data to write. | - | size | number | Yes | Size of the data to write. | - | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object. | + | buf | number[] | Yes| Data to write.| + | size | number | Yes| Size of the data to write.| + | offset | number | Yes| Start position of the data to write in the memory region associated with this **Ashmem** object.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | boolean | Returns **true** is the data is written successfully; returns **false** otherwise. | + | boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); @@ -3788,26 +3884,28 @@ Writes data to the shared file associated with this **Ashmem** object. ``` -### readFromAshmem +### readFromAshmem8+ readFromAshmem(size: number, offset: number): number[] Reads data from the shared file associated with this **Ashmem** object. +**System capability**: SystemCapability.Communication.IPC.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | size | number | Yes | Size of the data to read. | - | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object. | + | size | number | Yes| Size of the data to read.| + | offset | number | Yes| Start position of the data to read in the memory region associated with this **Ashmem** object.| -- Return values - | Type | Description | +- Return value + | Type| Description| | -------- | -------- | - | number[] | Data read. | + | number[] | Data read.| - Example - + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 34116c7c04b96f45167a8896710017851779d349..0f3a6ab7fb02dee588d22f92390a7ed6b731662e 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -563,7 +563,7 @@ Enables listening for error events of the UDPSocket connection. This API uses an **Example** ``` -let udp = socket.constructUDPSocketInstance() +let udp = socket.constructUDPSocketInstance(); udp.on('error', err => { console.log("on error, err:" + JSON.stringify(err)) }); @@ -591,7 +591,7 @@ Disables listening for error events of the UDPSocket connection. This API uses a **Example** ``` -let udp = socket.constructUDPSocketInstance() +let udp = socket.constructUDPSocketInstance(); let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 4cede020064f4a8ad43892a7940715bd49b52679..2070b5438c925d2b97bc0ac4f9321d0879388afa 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,1409 +1,1324 @@ -# WLAN +# WLAN ->**NOTE:** ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import -``` +## Modules to Import + +```js import wifi from '@ohos.wifi'; ``` -## wifi.isWifiActive +## wifi.isWifiActive -isWifiActive\(\): boolean +isWifiActive(): boolean Checks whether the WLAN is activated. -- Return values +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the WLAN is activated; returns false otherwise.

-
+- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is activated; returns **false** otherwise.| -## wifi.scan +## wifi.scan -scan\(\): boolean +scan(): boolean Starts a scan for WLAN. -- Return values +- Required permissions: + ohos.permission.SET_WIFI_INFO and ohos.permission.LOCATION - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the scan is successful; returns false otherwise.

-
+- System capability: + SystemCapability.Communication.WiFi.STA +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the scan is successful; returns **false** otherwise.| -## wifi.getScanInfos -getScanInfos\(\): Promise\> +## wifi.getScanInfos + +getScanInfos(): Promise<Array<WifiScanInfo>> Obtains the scan result. This method uses a promise to return the result. -- Return values +- Required permissions: + ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, or ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.STA - - - - - - - - - -

Type

-

Description

-

Promise< Array<WifiScanInfo> >

-

Promise used to return the scan result, which is a list of hotspot information.

-
+- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the scan result, which is a list of hotspots detected.| -## wifi.getScanInfos +## wifi.getScanInfos -getScanInfos\(callback: AsyncCallback\>\): void +getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void Obtains the scan result. This method uses an asynchronous callback to return the result. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback< Array<WifiScanInfo>>

-

Yes

-

Callback invoked to return the scan result, which is a list of hotspot information.

-
- - -- Example - - ``` - import wifi from '@ohos.wifi'; - - wifi.getScanInfos(result => { - var len = Object.keys(result).length; - console.log("wifi received scan info call back: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("timestamp: " + result[i].timestamp); - } - }); - - wifi.getScanInfos().then(result => { - var len = Object.keys(result).length; - console.log("wifi received scan info promise: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("timestamp: " + result[i].timestamp); - } - }); - ``` - - -## WifiScanInfo - -Defines the WLAN hotspot information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable/Writable

-

Description

-

ssid

-

string

-

Read-only

-

Hotspot service set identifier (SSID), in UTF-8 format.

-

bssid

-

string

-

Read-only

-

Basic service set identifier (BSSID) of the hotspot.

-

securityType

-

WifiSecurityType

-

Read-only

-

WLAN encryption type.

-

rssi

-

number

-

Read-only

-

Received Signal Strength Indicator (RSSI) of the hotspot, in dBm.

-

band

-

number

-

Read-only

-

Frequency band of the WLAN access point (AP).

-

frequency

-

number

-

Read-only

-

Frequency of the WLAN AP.

-

timestamp

-

number

-

Read-only

-

Timestamp.

-
- -## WifiSecurityType - -Enumerates the WLAN encryption types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

WIFI_SEC_TYPE_INVALID

-

0

-

Invalid encryption.

-

WIFI_SEC_TYPE_OPEN

-

1

-

Open encryption.

-

WIFI_SEC_TYPE_WEP

-

2

-

Wired equivalent privacy (WEP) encryption.

-

WIFI_SEC_TYPE_PSK

-

3

-

PSK encryption.

-

WIFI_SEC_TYPE_SAE

-

4

-

Simultaneous authentication of equals (SAE) encryption.

-
- -## wifi.getSignalLevel - -getSignalLevel\(rssi: number, band: number\): number +- Required permissions: + ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, or ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result, which is a list of hotspots detected.| + +- Example + ```js + import wifi from '@ohos.wifi'; + + wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + ``` + + +## WifiScanInfo + +Represents WLAN hotspot information. + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| +| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Read only| Hotspot capabilities.| +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| WLAN security type.| +| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| band | number | Read only| Frequency band of the WLAN access point (AP).| +| frequency | number | Read only| Frequency of the WLAN AP.| +| channelWidth | number | Read only| Bandwidth of the WLAN AP.| +| timestamp | number | Read only| Timestamp.| -Obtains the WLAN signal strength. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

rssi

-

number

-

Yes

-

RSSI of the hotspot, in dBm.

-

band

-

number

-

Yes

-

Frequency band of the WLAN AP.

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

Type

-

Description

-

number

-

Signal strength obtained. The value range is 0 to 4.

-
- - -## wifi.getIpInfo7+ - -getIpInfo\(\): IpInfo +## WifiSecurityType -Obtains IP information. +Enumerates the WLAN security types. -- Return values - - - - - - - - - - -

Type

-

Description

-

IpInfo

-

IP information obtained.

-
- - -## IpInfo - -Defines IP information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable/Writable

-

Description

-

ipAddress

-

number

-

Read-only

-

IP address.

-

gateway

-

number

-

Read-only

-

Gateway.

-

netmask

-

number

-

Read-only

-

Subnet mask.

-

primaryDns

-

number

-

Read-only

-

IP address of the preferred DNS server.

-

secondDns

-

number

-

Read-only

-

IP address of the alternate DNS server.

-

serverIp

-

number

-

Read-only

-

IP address of the DHCP server.

-

leaseDuration

-

number

-

Read-only

-

Lease duration of the IP address.

-
- -## wifi.isConnected7+ - -isConnected\(\): boolean +| **Name**| **Default Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type | +| WIFI_SEC_TYPE_OPEN | 1 | Open security type | +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP) | +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK) | +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE) | -Checks whether the WLAN is connected. -- Return values +## wifi.addUntrustedConfig7+ + +addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> + +Adds untrusted WLAN configuration. This method uses a promise to return the result. + +- Required permissions: + ohos.permission.SET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + +## WifiDeviceConfig + +Represents the WLAN configuration. + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| bssid | string | Read only| BSSID of the hotspot.| +| preSharedKey | string | Read only| Private key of the hotspot.| +| isHiddenSsid | boolean | Read only| Whether to hide the network.| +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type. | + + +## wifi.addUntrustedConfig7+ + +addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void + +Adds untrusted WLAN configuration. This method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.SET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + + +## wifi.removeUntrustedConfig7+ + +removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> + +Removes untrusted WLAN configuration. This method uses a promise to return the result. + +- Required permissions: + ohos.permission.SET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + + +## wifi.removeUntrustedConfig7+ + +removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void + +Removes untrusted WLAN configuration. This method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.SET_WIFI_INFO - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the WLAN is connected; returns false otherwise.

-
+- System capability: + SystemCapability.Communication.WiFi.STA +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| + | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| -## wifi.getLinkedInfo7+ -getLinkedInfo\(\): Promise +## wifi.getSignalLevel + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal strength. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| Signal strength of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | number | Signal strength obtained. The value range is [0, 4].| + + +## wifi.getLinkedInfo + +getLinkedInfo(): Promise<WifiLinkedInfo> Obtains WLAN connection information. This method uses a promise to return the result. -- Return values +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA - - - - - - - - - -

Type

-

Description

-

Promise<WifiLinkedInfo>

-

Promise used to return the WLAN connection information

-
+- Return value + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#WifiLinkedInfo)> | Promise used to return the WLAN connection information obtained.| -## wifi.getLinkedInfo7+ +## wifi.getLinkedInfo -getLinkedInfo\(callback: AsyncCallback\): void +getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void Obtains WLAN connection information. This method uses a callback to return the result. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<WifiLinkedInfo>

-

Yes

-

Callback invoked to return the WLAN connection information.

-
- -- Example - - ``` - import wifi from '@ohos.wifi'; - - wifi.getLinkedInfo(data => { - console.info("get wifi linked info [callback]: " + JSON.stringify(data)); - }); - - wifi.getLinkedInfo().then(data => { - console.info("get wifi linked info [promise]: " + JSON.stringify(data)); - }).catch(error => { - console.info("linked info promise then error"); - }); - ``` - - -## WifiLinkedInfo - -Defines the WLAN connection information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable/Writable

-

Description

-

ssid

-

string

-

Read-only

-

Hotspot SSID, in UTF-8 format.

-

bssid

-

string

-

Read-only

-

BSSID of the hotspot.

-

rssi

-

number

-

Read-only

-

RSSI of the hotspot, in dBm.

-

band

-

number

-

Read-only

-

Frequency band of the WLAN AP.

-

linkSpeed

-

number

-

Read-only

-

Speed of the WLAN AP.

-

frequency

-

number

-

Read-only

-

Frequency of the WLAN AP.

-

isHidden

-

boolean

-

Read-only

-

Whether the WLAN AP is hidden.

-

isRestricted

-

boolean

-

Read-only

-

Whether data volume is restricted at the WLAN AP.

-

macAddress

-

string

-

Read-only

-

MAC address of the device that sets up the WLAN connection.

-

ipAddress

-

number

-

Read-only

-

IP address of the device that sets up the WLAN connection.

-

connState

-

ConnState

-

Read-only

-

WLAN connection state.

-
- -## ConnState +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#WifiLinkedInfo)> | Yes| Callback invoked to return the WLAN connection information obtained.| + +- Example + ```js + import wifi from '@ohos.wifi'; + + wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); + }); + + wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); + }).catch(error => { + console.info("get linked info error"); + }); + ``` + + +## WifiLinkedInfo + +Represents the WLAN connection information. + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Read only| BSSID of the hotspot.| +| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| band | number | Read only| Frequency band of the WLAN AP.| +| linkSpeed | number | Read only| Speed of the WLAN AP.| +| frequency | number | Read only| Frequency of the WLAN AP.| +| isHidden | boolean | Read only| Whether the WLAN AP is hidden.| +| isRestricted | boolean | Read only| Whether data volume is restricted at the WLAN AP.| +| macAddress | string | Read only| MAC address of the device.| +| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| +| connState | [ConnState](#ConnState) | Read only| WLAN connection state.| + + +## ConnState Enumerates the WLAN connection states. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SCANNING

-

0

-

The device is scanning for available APs.

-

CONNECTING

-

1

-

A WLAN connection is being established.

-

AUTHENTICATING

-

2

-

An authentication is being performed for a WLAN connection.

-

OBTAINING_IPADDR

-

3

-

The IP address of the WLAN connection is being acquired.

-

CONNECTED

-

4

-

A WLAN connection is established.

-

DISCONNECTING

-

5

-

The WLAN connection is being disconnected.

-

DISCONNECTED

-

6

-

The WLAN connection is disconnected.

-

UNKNOWN

-

7

-

Failed to set up a WLAN connection.

-
- -## wifi.getCountryCode7+ - -getCountryCode\(\): string +| Name| Default Value| Description| +| -------- | -------- | -------- | +| SCANNING | 0 | The device is scanning for available APs.| +| CONNECTING | 1 | A WLAN connection is being established.| +| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.| +| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.| +| CONNECTED | 4 | A WLAN connection is established.| +| DISCONNECTING | 5 | The WLAN connection is being disconnected.| +| DISCONNECTED | 6 | The WLAN connection is disconnected.| +| UNKNOWN | 7 | Failed to set up a WLAN connection.| -Obtains the country code. -- Return values +## wifi.isConnected7+ - - - - - - - - - -

Type

-

Description

-

string

-

Country code obtained.

-
+isConnected(): boolean + +Checks whether the WLAN is connected. +- Required permissions: + ohos.permission.GET_WIFI_INFO -## wifi.isFeatureSupported7+ +- System capability: + SystemCapability.Communication.WiFi.STA -isFeatureSupported\(featureId: number\): boolean +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.isFeatureSupported7+ + +isFeatureSupported(featureId: number): boolean Checks whether the device supports the specified WLAN feature. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

featureId

-

number

-

Yes

-

Feature ID.

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

Type

-

Description

-

boolean

-

Returns true if the feature is supported; returns false otherwise.

-
- -- Enumerates the WLAN features. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Value

-

Description

-

0x0001

-

WLAN infrastructure mode.

-

0x0002

-

5 GHz bandwidth.

-

0x0004

-

Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature.

-

0x0008

-

Wi-Fi Direct.

-

0x0010

-

SoftAP.

-

0x0040

-

Wi-Fi AWare.

-

0x8000

-

WLAN AP/STA concurrency

-

0x8000000

-

WPA3 Personal (WPA-3 SAE) feature.

-

0x10000000

-

WPA3 Enterprise Suite B feature.

-

0x20000000

-

Enhanced open feature.

-
- - -## wifi.on\('wifiStateChange'\)7+ - -on\(type: "wifiStateChange", callback: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.Core + +- **Parameters** + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + +- Enumerates the WLAN features. + | Value| Description| + | -------- | -------- | + | 0x0001 | WLAN infrastructure mode| + | 0x0002 | 5 GHz bandwidth| + | 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| + | 0x0008 | Wi-Fi Direct| + | 0x0010 | SoftAP| + | 0x0040 | Wi-Fi AWare| + | 0x8000 | WLAN AP/STA concurrency| + | 0x8000000 | WPA3 Personal (WPA-3 SAE)| + | 0x10000000 | WPA3-Enterprise Suite-B | + | 0x20000000 | Enhanced open feature| + + +## wifi.getIpInfo7+ + +getIpInfo(): IpInfo + +Obtains IP information. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#IpInfo) | IP information obtained.| + + +## IpInfo7+ + +Represents IP information. + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| ipAddress | number | Read only| IP address. | +| gateway | number | Read only| Gateway. | +| netmask | number | Read only| Subnet mask. | +| primaryDns | number | Read only| IP address of the preferred DNS server. | +| secondDns | number | Read only| IP address of the alternate DNS server. | +| serverIp | number | Read only| IP address of the DHCP server. | +| leaseDuration | number | Read only| Lease duration of the IP address. | + + +## wifi.getCountryCode7+ + +getCountryCode(): string + +Obtains the country code. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.Core + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.getP2pLinkedInfo8+ + +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> + +Obtains peer-to-peer (P2P) connection information. This method uses a promise to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise used to return the P2P connection information obtained.| + + +## wifi.getP2pLinkedInfo8+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P connection information. This method uses a callback to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback used to return the P2P connection information obtained.| + + +## WifiP2pLinkedInfo8+ + +Represents the WLAN connection information. + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#P2pConnectState) | Read only| P2P connection state.| +| isGroupOwner | boolean | Read only| Whether it is a group.| +| groupOwnerAddr | string | Read only| MAC address of the group.| + + +## P2pConnectState8+ + +Enumerates the P2P connection states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | Disconnected| +| CONNECTED | 1 | Connected| + + +## wifi.getCurrentGroup8+ + +getCurrentGroup(): Promise<WifiP2pGroupInfo> + +Obtains the current P2P group information. This method uses a promise to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Promise used to return the P2P group information obtained.| + + +## wifi.getCurrentGroup8+ + +getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void + +Obtains the P2P group information. This method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback used to return the P2P group information obtained.| + + +## WifiP2pGroupInfo8+ + +Represents the P2P group information. + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Read only| Whether it is a group.| +| ownerInfo | [WifiP2pDevice](#WifiP2pDevice) | Read only| Device information of the group.| +| passphrase | string | Read only| Private key of the group.| +| interface | string | Read only| Interface name.| +| groupName | string | Read only| Group name.| +| networkId | number | Read only| Network ID.| +| frequency | number | Read only| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#WifiP2pDevice) | Read only| List of connected devices.| +| goIpAddress | string | Read only| IP address of the group.| + +## WifiP2pDevice8+ + +Represents the P2P device information. + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| deviceName | string | Read only| Device name.| +| deviceAddress | string | Read only| MAC address of the device.| +| primaryDeviceType | string | Read only| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | Read only| Device status.| +| groupCapabilitys | number | Read only| Group capabilities.| + +## P2pDeviceStatus8+ + +Enumerates the device states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected| +| INVITED | 1 | Invited| +| FAILED | 2 | Failed| +| AVAILABLE | 3 | Available| +| UNAVAILABLE | 4 | Unavailable| + + +## wifi.getP2pPeerDevices8+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> + +Obtains the list of peer devices in a P2P connection. This method uses a promise to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise used to return the peer device list obtained.| + + +## wifi.getP2pPeerDevices8+ + +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the list of peer devices in a P2P connection. This method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback used to return the peer device list obtained.| + + +## wifi.createGroup8+ + +createGroup(config: WifiP2PConfig): boolean; + +Creates a P2P group. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- **Parameters** + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Group configuration.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +## WifiP2PConfig8+ + +Represents P2P configuration. + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| deviceAddress | string | Read only| Device address.| +| netId | number | Read only| Network ID. The value **-1** indicates that a temporary group, and **-2** indicates that a persistent group.| +| passphrase | string | Read only| Private key of the group.| +| groupName | string | Read only| Name of the group.| +| goBand | [GroupOwnerBand](#GroupOwnerBand) | Read only| Bandwidth of the group.| + + +## GroupOwnerBand8+ + +Enumerates the P2P group bandwidths. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| GO_BAND_AUTO | 0 | Auto| +| GO_BAND_2GHZ | 1 | 2 GHz| +| GO_BAND_5GHZ | 2 | 5 GHz| + +## wifi.removeGroup8+ + +removeGroup(): boolean; + +Removes a P2P group. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.p2pConnect8+ + +p2pConnect(config: WifiP2PConfig): boolean; + +Sets up a P2P connection. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- **Parameters** + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Connection configuration.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +- Example + ```js + import wifi from '@ohos.wifi'; + + var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); + } + wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); + } + wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); + } + wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + var recvP2pPersistentGroupChangeFunc = result => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); + } + wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifi.startDiscoverDevices()); + ``` + +## wifi.p2pCancelConnect8+ + +p2pCancelConnect(): boolean; + +Cancels this P2P connection. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.startDiscoverDevices8+ + +startDiscoverDevices(): boolean; + +Starts to discover devices. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.stopDiscoverDevices8+ + +stopDiscoverDevices(): boolean; + +Stops discovering devices. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.on('wifiStateChange')7+ + +on(type: "wifiStateChange", callback: Callback<number>): void Registers the WLAN state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiStateChange.

-

callback

-

Callback<number>

-

Yes

-

Callback invoked to return the WLAN state.

-
- - -- Enumerates the WLAN states. - - - - - - - - - - - - - - - - - - - -

Value

-

Description

-

0

-

Deactivated.

-

1

-

Activated.

-

2

-

Activating.

-

3

-

Deactivating.

-
- - -## wifi.off\('wifiStateChange'\)7+ - -off\(type: "wifiStateChange", callback?: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + +- Enumerates the WLAN states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Deactivated| + | 1 | Activated| + | 2 | Activating| + | 3 | Deactivating| + + +## wifi.off('wifiStateChange')7+ + +off(type: "wifiStateChange", callback?: Callback<number>): void Unregisters the WLAN state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiStateChange.

-

callback

-

Callback<number>

-

No

-

Callback used to report the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

-
- - -- Example - - ``` - import wifi from '@ohos.wifi'; - import { EventListener } from '@ohos.wifi'; - - var WIFI_POWER_STATE = "wifiStateChange"; - var listener = new EventListener(); - - var recvPowerNotifyFunc = result => { - console.info("power state receive event: " + result); - } - - // Register event - listener.on(WIFI_POWER_STATE, recvPowerNotifyFunc); - - // Unregister event - listener.off(WIFI_POWER_STATE, recvPowerNotifyFunc); - ``` - - -## wifi.on\('wifiConnectionChange'\)7+ - -on\(type: "wifiConnectionChange", callback: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +- Example + ```js + import wifi from '@ohos.wifi'; + + var WIFI_POWER_STATE = "wifiStateChange"; + var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); + } + + // Register event + wifi.on(WIFI_POWER_STATE, recvPowerNotifyFunc); + + // Unregister event + wifi.off(WIFI_POWER_STATE, recvPowerNotifyFunc); + ``` + + +## wifi.on('wifiConnectionChange')7+ + +on(type: "wifiConnectionChange", callback: Callback<number>): void Registers the WLAN connection state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiConnectionChange.

-

callback

-

Callback<number>

-

Yes

-

Callback invoked to return the WLAN connection state.

-
- - -- Enumerates the WLAN connection states. - - - - - - - - - - - - - -

Value

-

Description

-

0

-

Disconnected.

-

1

-

Connected.

-
- - -## wifi.off\('wifiConnectionChange'\)7+ - -off\(type: "wifiConnectionChange", callback?: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + +- Enumerates the WLAN connection states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Disconnected| + | 1 | Connected| + + +## wifi.off('wifiConnectionChange')7+ + +off(type: "wifiConnectionChange", callback?: Callback<number>): void Unregisters the WLAN connection state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiConnectionChange.

-

callback

-

Callback<number>

-

No

-

Callback used to report the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

-
- - -## wifi.on\('wifiScanStateChange'\)7+ - -on\(type: "wifiScanStateChange", callback: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback used to report the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiScanStateChange')7+ + +on(type: "wifiScanStateChange", callback: Callback<number>): void Registers the WLAN scan state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiScanStateChange.

-

callback

-

Callback<number>

-

Yes

-

Callback invoked to return the WLAN scan state.

-
- - -- Enumerates the WLAN scan states. - - - - - - - - - - - - - -

Value

-

Description

-

0

-

The scan failed.

-

1

-

The scan is successful.

-
- - -## wifi.off\('wifiScanStateChange'\)7+ - -off\(type: "wifiScanStateChange", callback?: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + +- Enumerates the WLAN scan states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Scan failed| + | 1 | Scan successful| + + +## wifi.off('wifiScanStateChange')7+ + +off(type: "wifiScanStateChange", callback?: Callback<number>): void Unregisters the WLAN scan state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiScanStateChange.

-

callback

-

Callback<number>

-

No

-

Callback used to report the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

-
- -## wifi.on\('wifiRssiChange'\)7+ - -on\(type: "wifiRssiChange", callback: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiRssiChange')7+ + +on(type: "wifiRssiChange", callback: Callback<number>): void Registers the RSSI state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiRssiChange.

-

callback

-

Callback<number>

-

Yes

-

Callback invoked to return the RSSI, in dBm.

-
- - -## wifi.off\('wifiRssiChange'\)7+ - -off\(type: "wifiRssiChange", callback?: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + + +## wifi.off('wifiRssiChange')7+ + +off(type: "wifiRssiChange", callback?: Callback<number>): void Unregisters the RSSI state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is wifiRssiChange.

-

callback

-

Callback<number>

-

No

-

Callback used to report the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

-
- - -## wifi.on\('hotspotStateChange'\)7+ - -on\(type: "hotspotStateChange", callback: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.STA + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | No| Callback used to return the RSSI, in dBm. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('hotspotStateChange')7+ + +on(type: "hotspotStateChange", callback: Callback<number>): void Registers the hotspot state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is hotspotStateChange.

-

callback

-

Callback<number>

-

Yes

-

Callback invoked to return the hotspot state.

-
- - -- Enumerates the hotspot states. - - - - - - - - - - - - - - - - - - - -

Value

-

Description

-

0

-

Deactivated.

-

1

-

Activated.

-

2

-

Activating.

-

3

-

Deactivating.

-
- - -## wifi.off\('hotspotStateChange'\)7+ - -off\(type: "hotspotStateChange", callback?: Callback\): void +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.AP + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + +- Enumerates the hotspot states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Deactivated| + | 1 | Activated| + | 2 | Activating| + | 3 | Deactivating| + + +## wifi.off('hotspotStateChange')7+ + +off(type: "hotspotStateChange", callback?: Callback<number>): void Unregisters the hotspot state change events. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is hotspotStateChange.

-

callback

-

Callback<number>

-

No

-

Callback used to report the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

-
+- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.AP + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pStateChange')8+ + +on(type: "p2pStateChange", callback: Callback<number>): void + +Registers the P2P status change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + +- Enumerates the P2P states. + | **Value**| **Description**| + | -------- | -------- | + | 1 | Available| + | 2 | Opening| + | 3 | Opened| + | 4 | Closing| + | 5 | Closed| + +## wifi.off('p2pStateChange')8+ + +off(type: "p2pStateChange", callback?: Callback<number>): void + +Unregisters the P2P state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + + ## wifi.on('p2pConnectionChange')8+ + +on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void + +Registers the P2P connection state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback invoked to return the P2P connection state.| + + +## wifi.off('p2pConnectionChange')8+ + +off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void + +Unregisters the P2P connection state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDeviceChange')8+ + +on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void + +Registers the P2P device state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P device state.| + + +## wifi.off('p2pDeviceChange')8+ + +off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void + +Unregisters the P2P device state change events. + +- Required permissions: + ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPeerDeviceChange')8+ + +on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void + +Registers the P2P peer device state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P peer device state.| + + +## wifi.off('p2pPeerDeviceChange')8+ + +off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void + +Unregisters the P2P peer device state change events. + +- Required permissions: + ohos.permission.LOCATION + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPersistentGroupChange')8+ + +on(type: "p2pPersistentGroupChange", callback: Callback<void>): void + +Registers the P2P persistent group state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + + +## wifi.off('p2pPersistentGroupChange')8+ + +off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void + +Unregisters the P2P persistent group state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDiscoveryChange')8+ + +on(type: "p2pDiscoveryChange", callback: Callback<number>): void + +Registers the P2P discovered device state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.P2P + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the state of the P2P discovered device.| + +- Enumerates the states of P2P discovered devices. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Initial state| + | 1 | Discovered| + + +## wifi.off('p2pDiscoveryChange')8+ + +off(type: "p2pDiscoveryChange", callback?: Callback<number>): void + +Unregisters the P2P discovered device state change events. + +- Required permissions: + ohos.permission.GET_WIFI_INFO +- System capability: + SystemCapability.Communication.WiFi.P2P +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback used to return the state of the P2P discovered device. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md new file mode 100644 index 0000000000000000000000000000000000000000..d3b1c26cd6eddc26f04dd3a5dc64c885f96ca9ca --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -0,0 +1,153 @@ +# WLAN + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+The APIs described in this document are used only for non-universal products, such as routers. + + +## Modules to Import + +```js +import wifiext from '@ohos.wifiext'; +``` + +## wifiext.enableHotspot + +enableHotspot(): boolean; + +Enables the WLAN hotspot. + +- Required permissions: + ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.disableHotspot + +disableHotspot(): boolean; + +Disables the WLAN hotspot. + +- Required permissions: + ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(): Promise<Array<PowerModel>> + +Obtains the supported power models. The method uses a promise to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#PowerModel)>> | Promise used to return the power models obtained.| + + +## PowerModel + +Enumerates of the power models. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| SLEEPING | 0 | Sleeping| +| GENERAL | 1 | General| +| THROUGH_WALL | 2 | Through_wall| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void + +Obtains the supported power models. The method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback used to return the power models obtained.| + + +## wifiext.getPowerModel + +getPowerModel(): Promise<PowerModel> + +Obtains the power model. The method uses a promise to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#PowerModel)> | Promise used to return the power model obtained.| + + +## wifiext.getPowerModel + +getPowerModel(callback: AsyncCallback<PowerModel>): void + +Obtains the power model. The method uses an asynchronous callback to return the result. + +- Required permissions: + ohos.permission.GET_WIFI_INFO + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback invoked to return the power mode obtained.| + + +## wifiext.setPowerModel + +setPowerModel(model: PowerModel) : boolean; + + Sets the power model. + +- Required permissions: + ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +- System capability: + SystemCapability.Communication.WiFi.HotspotExt + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Power model to set.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 2c6cea49567c3fd4f888983ae387191d3ef3dcf7..5877e10c6c2ce94cd929ca648fb1b3c6ea00e27a 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -73,6 +73,7 @@ - [TextInput](ts-basic-components-textinput.md) - [TextPicker](ts-basic-components-textpicker.md) - [TextTimer](ts-basic-components-texttimer.md) + - [TimePicker](ts-basic-components-timepicker.md) - [Toggle](ts-basic-components-toggle.md) - [TextClock](ts-basic-components-textclock.md) - [Web](ts-basic-components-web.md) @@ -143,6 +144,7 @@ - [Action Sheet](ts-methods-action-sheet.md) - [Custom Dialog Box](ts-methods-custom-dialog-box.md) - [Date Picker Dialog Box](ts-methods-datepicker-dialog.md) + - [Time Picker Dialog Box](ts-methods-timepicker-dialog.md) - [Text Picker Dialog Box](ts-methods-textpicker-dialog.md) - [Menu](ts-methods-menu.md) - Appendix diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 07518d184b6f6cf06476f439b04f6396c89b0b35..f14fcd3c6df29523f7fe798de697ca69a04bbdd9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -1,73 +1,61 @@ # DatePicker - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -The **<DatePicker>** component allows users to select date and time. +The **\** component allows users to select a date from the given range. ## Required Permissions -None +No ## Child Components -None +No ## APIs -DatePicker(value:{start?: Date, end?: Date, selected?: Date, type?: DatePickerType}) +DatePicker(options?: DatePickerOptions) -Creates a date picker that allows users to select a date or time within the specified range. +Creates a date picker in the given date range. -- Parameters - | Name | Type | Mandatory | Default Value | Description | +- options parameters + | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | - | start | Date | No | Date('1970-1-1') | Start date of the date picker. | - | end | Date | No | Date('2100-12-31') | End date of the date picker. | - | selected | Date | No | Current system date or time | Selected date when **type** is set to **DatePickerType.Date** and selected time when **type** is set to **DatePickerType.Time**. | - | type | DatePickerType | No | DatePickerType.Date | Picker type, which can be date picker and time picker. The date picker is used by default. | - -- DatePickerType enums - | Name | Description | - | -------- | -------- | - | Date | Date picker. | - | Time | Time picker. | + | start | Date | No| Date('1970-1-1') | Start date of the picker.| + | end | Date | No| Date('2100-12-31') | End date of the picker.| + | selected | Date | No| Current system date| Date of the selected item.| ## Attributes -| Name | Type | Default Value | Description | -| -------- | -------- | -------- |-------- | -| lunar | boolean | false | Whether to display the lunar calendar.
- **true**: The lunar calendar is displayed.
- **false**: The lunar calendar is not displayed. | -| useMilitaryTime | boolean | false | Whether the display time is in 24-hour format. The value cannot be dynamically modified. | +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| lunar | boolean | false | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.| ## Events -| Name | Description | +| Name| Description| | -------- | -------- | -| onChange(callback: (value: DatePickerResult) => void) | This event is triggered when a date or time is selected. | +| onChange(callback: (value: DatePickerResult) => void) | Triggered when a date is selected.| -- DatePickerResult - | Name | Type | Description | - | -------- | -------- | -------- | - | year | number | Year of the selected date (when **type** is **DatePickerType.Date**). | - | month | number | Month of the selected date (when **type** is **DatePickerType.Date**). | - | day | number | Date of the selected date (when **type** is **DatePickerType.Date**). | - | hour | number | Hour portion of the selected time (when **type** is **DatePickerType.Time**). | - | minute | number | Minute portion of the selected time (when **type** is **DatePickerType.Time**). | +### DatePickerResult +| Name| Type| Description| +| -------- | -------- | -------- | +| year | number | Year of the selected date.| +| month | number | Month of the selected date.| +| day | number | Day of the selected date.| ## Example -### Date Picker (with Lunar Calendar) - +### Date Picker Sample Code (With Lunar Calendar) ``` @Entry @@ -79,9 +67,8 @@ struct DatePickerExample01 { Column() { DatePicker({ start: new Date('1970-1-1'), - end: new Date('2200-1-1'), + end: new Date('2100-1-1'), selected: this.selectedDate, - type: DatePickerType.Date }) .lunar(true) .onChange((date: DatePickerResult) => { @@ -93,8 +80,7 @@ struct DatePickerExample01 { ``` -### Date Picker (Without Lunar Calendar) - +### Date Picker Sample Code (No Lunar Calendar) ``` @Entry @@ -106,9 +92,8 @@ struct DatePickerExample02 { Column() { DatePicker({ start: new Date('1970-1-1'), - end: new Date('2200-1-1'), + end: new Date('2100-1-1'), selected: this.selectedDate, - type: DatePickerType.Date }) .lunar(false) .onChange((date: DatePickerResult) => { @@ -120,31 +105,3 @@ struct DatePickerExample02 { ``` - -### Time Picker - - -``` -@Entry -@Component -struct DatePickerExample03 { - private selectedTime: Date = new Date('2021-9-29 08:00:00') - - build() { - Column() { - DatePicker({ - start: new Date('00:00:00'), - end: new Date('23:59:59'), - selected: this.selectedTime, - type: DatePickerType.Time - }) - .useMilitaryTime(true) - .onChange((date: DatePickerResult) => { - console.info('select current date is: ' + JSON.stringify(date)) - }) - }.width('100%') - } -} -``` - -![en-us_image_0000001256858401](figures/en-us_image_0000001256858401.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md new file mode 100644 index 0000000000000000000000000000000000000000..24b1ac6d59eb51962ee98a000ea19fb0b22658c7 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -0,0 +1,77 @@ +# TimePicker + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + + +The **\** component allows users to select a time from the given range. + + +## Required Permissions + +No + + +## Child Components + +No + + +## APIs + +TimePicker(options?: TimePickerOptions) + +Creates a time picker whose default time range is from 00:00 to 23:59. + +- options parameters + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | selected | Date | No| Current system time| Time of the selected item.| + + +## Attributes + +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| useMilitaryTime | boolean | false | Whether to display time in 24-hour format. The value cannot be modified dynamically.| + + +## Events + +| Name| Description| +| -------- | -------- | +| onChange(callback: (value: TimePickerResult ) => void) | Triggered when a time is selected.| + +### TimePickerResult +| Name| Type| Description| +| -------- | -------- | -------- | +| hour | number | Hour portion of the selected time.| +| minute | number | Minute portion of the selected time.| + + +## Example + + +### Time Picker + +``` +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('08-00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime, + }) + .useMilitaryTime(true) + .onChange((date: TimePickerResult) => { + console.info('select current date is: ' + JSON.stringify(date)) + }) + }.width('100%') + } +} +``` + +![en-us_image_0000001251292933](figures/en-us_image_0000001251292933.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index ba0a5716aea4ad26811ba541e3f2053ee48b919f..33f5b2b99a98549ba58125493535f8efbad948b5 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -You can display a date or time picker in a dialog box to allow users to select a date or time from the given range. +You can display a date picker in a dialog box to allow users to select a date from the given range. ## Required Permissions @@ -11,22 +11,20 @@ None ## DatePickerDialog.show -show(options?: DatePickerDialogOption) +show(options?: DatePickerDialogOptions) -Shows a date or time picker in the given settings. +Defines and displays a date picker dialog box. -- DatePickerDialogOption parameters +- options parameters | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | | start | Date | No| Date('1970-1-1') | Start date of the picker.| | end | Date | No| Date('2100-12-31') | End date of the picker.| - | selected | Date | No| Current system date or time| Date or time of the selected item in the picker. When **type** is set to **DatePickerType.Date**, this parameter indicates the date of the selected item. When **type** is set to **DatePickerType.Time**, this parameter indicates the time of the selected item.| - | type | [DatePickerType](ts-basic-components-datepicker.md) | No| DatePickerType.Date | Picker type, which can be the date picker and time picker.| + | selected | Date | No| Current system date| Date of the selected item.| | lunar | boolean | No| false | Whether to display the lunar calendar.| - | useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| - | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md)) => void | No| - | Triggered when the OK button in the dialog box is clicked.| + | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Triggered when the OK button in the dialog box is clicked.| | onCancel | () => void | No| - | Triggered when the Cancel button in the dialog box is clicked.| - | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md)) => void | No| - | Triggered when the selected item in the picker changes.| + | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Triggered when the selected item in the picker changes.| ## Example @@ -36,8 +34,6 @@ Shows a date or time picker in the given settings. @Component struct DatePickerDialogExample01 { @State isLunar: boolean = true - @State isUseMilitaryTime: boolean = false - @State datePickerType: DatePickerType = DatePickerType.Date selectedDate: Date = new Date("2000-1-1") build() { @@ -48,15 +44,10 @@ struct DatePickerDialogExample01 { start: new Date("2000-1-1"), end: new Date("2005-1-1"), selected: this.selectedDate, - type: this.datePickerType, lunar: this.isLunar, - useMilitaryTime: this.isUseMilitaryTime, onAccept: (value: DatePickerResult) => { + this.selectedDate.setFullYear(value.year, value.month, value.day) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - if (this.datePickerType == DatePickerType.Date) { - this.selectedDate.setFullYear(value.year, value.month, value.day) - } else if (this.datePickerType == DatePickerType.Time) { - this.selectedDate.setHours(value.hour, value.minute, value.second) } }, onCancel: () => { @@ -77,8 +68,6 @@ struct DatePickerDialogExample01 { @Component struct DatePickerDialogExample02 { @State isLunar: boolean = false - @State isUseMilitaryTime: boolean = false - @State datePickerType: DatePickerType = DatePickerType.Date selectedDate: Date = new Date("2000-1-1") build() { @@ -89,97 +78,10 @@ struct DatePickerDialogExample02 { start: new Date("2000-1-1"), end: new Date("2005-1-1"), selected: this.selectedDate, - type: this.datePickerType, lunar: this.isLunar, - useMilitaryTime: this.isUseMilitaryTime, onAccept: (value: DatePickerResult) => { + this.selectedDate.setFullYear(value.year, value.month, value.day) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - if (this.datePickerType == DatePickerType.Date) { - this.selectedDate.setFullYear(value.year, value.month, value.day) - } else if (this.datePickerType == DatePickerType.Time) { - this.selectedDate.setHours(value.hour, value.minute, value.second) - } - }, - onCancel: () => { - console.info("DatePickerDialog:onCancel()") - }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) - } - }) - }) - } - } -} -``` -### Time Picker Sample Code (24-Hour Clock) -``` -@Entry -@Component -struct DatePickerDialogExample03 { - @State isLunar: boolean = false - @State isUseMilitaryTime: boolean = true - @State datePickerType: DatePickerType = DatePickerType.Time - selectedDate: Date = new Date("2000-1-1") - - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("DatePickerDialog").onClick(() => { - DatePickerDialog.show({ - start: new Date("2000-1-1"), - end: new Date("2005-1-1"), - selected: this.selectedDate, - type: this.datePickerType, - lunar: this.isLunar, - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: DatePickerResult) => { - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - if (this.datePickerType == DatePickerType.Date) { - this.selectedDate.setFullYear(value.year, value.month, value.day) - } else if (this.datePickerType == DatePickerType.Time) { - this.selectedDate.setHours(value.hour, value.minute, value.second) - } - }, - onCancel: () => { - console.info("DatePickerDialog:onCancel()") - }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) - } - }) - }) - } - } -} -``` -### Time Picker Sample Code (12-Hour Clock) -``` -@Entry -@Component -struct DatePickerDialogExample04 { - @State isLunar: boolean = false - @State isUseMilitaryTime: boolean = false - @State datePickerType: DatePickerType = DatePickerType.Time - selectedDate: Date = new Date("2000-1-1") - - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("DatePickerDialog").onClick(() => { - DatePickerDialog.show({ - start: new Date("2000-1-1"), - end: new Date("2005-1-1"), - selected: this.selectedDate, - type: this.datePickerType, - lunar: this.isLunar, - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: DatePickerResult) => { - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - if (this.datePickerType == DatePickerType.Date) { - this.selectedDate.setFullYear(value.year, value.month, value.day) - } else if (this.datePickerType == DatePickerType.Time) { - this.selectedDate.setHours(value.hour, value.minute, value.second) } }, onCancel: () => { diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md new file mode 100644 index 0000000000000000000000000000000000000000..5c0bc59793f8386e1cc1e93d1b5c6d11da00f8b7 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -0,0 +1,86 @@ +# Time Picker Dialog Box + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + +You can display a time picker in a dialog box to allow users to select a time from the given range, which is from 00:00 to 23:59 by default. + +## Required Permissions + +None + +## TimePickerDialog.show + +show(options?: TimePickerDialogOptions) + +Defines and displays a time picker dialog box. + +- options parameters + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | selected | Date | No| Current system time| Time of the selected item.| + | useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| + | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Triggered when the OK button in the dialog box is clicked.| + | onCancel | () => void | No| - | Triggered when the Cancel button in the dialog box is clicked.| + | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Triggered when the selected item in the picker changes.| + +## Example + +### Time Picker Sample Code (24-Hour Clock) +``` +@Entry +@Component +struct TimePickerDialogExample01 { + @State isUseMilitaryTime: boolean = true + + build() { + Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center }) { + Button("TimePickerDialog").onClick(() => { + TimePickerDialog.show({ + useMilitaryTime: this.isUseMilitaryTime, + onAccept: (value: TimePickerResult) => { + this.selectedDate.setHours(value.hour, value.minute, value.second) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()") + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) + } + }) + }) + } + } +} +``` +### Time Picker Sample Code (12-Hour Clock) +``` +@Entry +@Component +struct TimePickerDialogExample02 { + @State isUseMilitaryTime: boolean = false + + build() { + Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center }) { + Button("TimePickerDialog").onClick(() => { + TimePickerDialog.show({ + useMilitaryTime: this.isUseMilitaryTime, + onAccept: (value: TimePickerResult) => { + this.selectedDate.setHours(value.hour, value.minute, value.second) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()") + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) + } + }) + }) + } + } +} +``` diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 4f312d93b860af28ea806a15a17fe6fb54552ea5..71699978011412397074ac275ab88d6143835626 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1,4 +1,4 @@ -# Application Development +# OpenHarmony Application Development Documentation - [Application Development Overview](application-dev-guide.md) - Quick Start diff --git a/en/device-dev/driver/driver-peripherals-sensor-des.md b/en/device-dev/driver/driver-peripherals-sensor-des.md index 4b54238b70d642fbc49825ef2324d9bc31644def..4f7eef84c1b304ae3208ff8e752b88f84256f3ab 100644 --- a/en/device-dev/driver/driver-peripherals-sensor-des.md +++ b/en/device-dev/driver/driver-peripherals-sensor-des.md @@ -1,848 +1,530 @@ -# Sensor - -## Overview - -The sensor driver module provides APIs for upper-layer sensor services to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data, and setting sensor options. The sensor driver model is developed based on the Hardware Driver Foundation \(HDF\) and supports functions such as cross-OS migration and differentiated device configuration. The following figure shows the architecture of the sensor driver model. - -**Figure 1** Architecture of the sensor driver model -![](figures/architecture-of-the-sensor-driver-model.png "architecture-of-the-sensor-driver-model") - -The sensor driver model offers the following APIs: - -- Hardware Driver Interfaces \(HDIs\) for sensors: These HDIs facilitate service development. -- APIs for implementing sensor driver model capabilities: These APIs implement the capabilities of registering, loading, and unregistering sensor drivers as well as detecting sensor devices depending on the HDF. The APIs include normalized APIs for sensor devices of the same type, APIs for parsing register configurations, abstract APIs for bus access, and abstract platform APIs. -- APIs to be implemented by developers: Based on the HDF Configuration Source \(HCS\), developers can implement differentiated configuration for sensors of the same type and serialized configuration of sensor device parameters. Some sensor device operations can be abstracted as APIs to simplify sensor driver development. - -## Available APIs - -The following table lists the APIs provided by the sensor driver model. - -**Table 1** External APIs provided by the sensor driver model - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Query

-

int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count)

-

Obtains information about all sensors in the system. The information about a sensor generally includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum measurement range, accuracy, and power.

-

Setting

-

int32_t Enable(int32_t sensorId)

-

Enables the sensor that has been subscribed to. The subscriber can obtain the sensor data only after the sensor is enabled.

-

int32_t Disable(int32_t sensorId)

-

Disables a sensor.

-

int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval)

-

Sets the data sampling interval and data reporting interval for the specified sensor.

-

int32_t SetMode(int32_t sensorTypeId, SensorUser *user, int32_t mode)

-

Sets the data reporting mode for the specified sensor.

-

int32_t SetOption(int32_t sensorId, uint32_t option)

-

Sets options for the specified sensor, including its measurement range and accuracy.

-

Data subscription and unsubscription

-

int32_t Register(RecordDataCallback cb)

-

Registers the callback for reporting sensor data to the subscriber.

-

int32_t Unregister(void)

-

Unregisters the callback for reporting sensor data.

-

Instance creation

-

const struct SensorInterface *NewSensorInterfaceInstance(void)

-

Creates a SensorInterface instance.

-

int32_t FreeSensorInterfaceInstance(void)

-

Releases the SensorInterface instance.

-
- -The following table lists the APIs provided by the sensor driver model for driver developers. You can directly call these APIs without any implementations. - -**Table 2** APIs provided by the sensor driver model for driver developers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Device management

-

int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo)

-

Adds a sensor of the current type to the sensor management module.

-

int32_t DeleteSensorDevice(int32_t sensorId)

-

Deletes a specified sensor from the sensor management module.

-

int32_t ReportSensorEvent(const struct SensorReportEvent *events)

-

Reports data of a specified sensor type.

-

Abstract bus and platform operations

-

int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen)

-

Reads sensor configuration data from the sensor register based on the bus configuration.

-

int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len)

-

Writes sensor configuration data to the sensor register based on the bus configuration.

-

int32_t CreateSensorThread(struct OsalThread *thread, OsalThreadEntry threadEntry, char *name, void *entryPara)

-

Creates a scheduled thread for a specified sensor to process sensor data reporting.

-

void DestroySensorThread(struct OsalThread *thread, uint8_t *status);

-

Destroys the scheduled thread created for the sensor.

-

Common configuration

-

int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group);

-

Sets the sensor register group configuration based on the sensor bus type.

-

Configuration parsing

-

-

int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config)

-

Obtains basic configuration information such as sensor, bus, and attribute configurations based on the HCS resource configuration of the sensor device, and initializes the basic configuration data structure.

-

int32_t ParseSensorRegConfig(struct SensorCfgData *config)

-

Parses the register group information based on the HCS resource configuration of the sensor device and initializes the configuration data structure.

-

void ReleaseSensorAllRegConfig(struct SensorCfgData *config)

-

Releases the resources allocated to the sensor configuration data structure.

-

int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg)

-

Obtains the sensor bus handle information.

-

int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg)

-

Releases the sensor bus handle information.

-
- -The following table lists the APIs that need to be implemented by driver developers. - -**Table 3** APIs that need to be implemented by driver developers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Basic functions

-

int32_t init(void)

-

Initializes the configuration of a sensor device after it is detected.

-

int32_t GetInfo(struct SensorBasicInfo *info)

-

Obtains the basic information about the current sensor device from the HCS of sensor devices.

-

int32_t Enable(void)

-

Enables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.

-

int32_t Disable(void)

-

Disables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.

-

int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval)

-

Sets the processing time of the data reporting thread for the current sensor device based on the data sampling interval and data reporting interval.

-

int32_t SetMode(int32_t mode)

-

Sets the data reporting mode of the current sensor device.

-

int32_t SetOption(uint32_t option)

-

Sets the register configuration such as the measurement range and accuracy based on sensor options.

-

void ReadSensorData(void)

-

Reads sensor data.

-
- -For details about the API implementation, see [Development Example](#section257750691). - -## How to Develop - -Regardless of the OS and system on a chip \(SoC\), the sensor driver is developed based on the HDF, platform, and OSAL APIs to provide a unified driver model for sensor devices. This section uses the acceleration sensor as an example to describe how to develop a sensor driver. - -1. Register the acceleration sensor driver. The HDF provides a unified driver management model. The HDF identifies and loads the target module driver based on the configuration of the acceleration sensor module. -2. Initialize and deinitialize the acceleration sensor driver. Using the **init** function, the HDF starts loading the sensor device driver and allocating configuration resources for sensor device data, respectively. Using the **release** function, the HDF releases the resources and configurations loaded by the driver. -3. Parse the configurations of the acceleration sensor register group. For different types of sensors, you must configure their respective HCS configuration files in the HCS, check whether the sensor device is in position during the device driver startup, and then load the corresponding configuration file to generate the configuration structure object. -4. Implement APIs for acceleration sensor driver operations. The driver APIs for various types of sensors, such as **init**, **GetInfo**, **Enable**, **Disable**, **SetBatch**, **SetMode**, **SetOption**, and **ReadSensorData**, are normalized to deliver sensor driver configurations and report sensor data. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The sensor driver model provides a collection of APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, general configuration, and configuration parsing capabilities. For details about the APIs, see [Table 2](#table1156812588320). You need to implement the following APIs: some operations to perform on sensors \([Table 3](#table1083014911336)\), differentiated data configuration of the sensor HCS, and verification of basic driver functions. - -## Development Example - -This section uses a code example to demonstrate how to load and start the acceleration sensor driver based on the HDF driver model. For details about the mechanism, see [Driver Development](driver-hdf-development.md). This example uses the Bosch BMI160 acceleration sensor that communicates over I2C. - -1. Register the driver entry of the acceleration sensor. - -- Implementation of the entry function - -``` -/* Register the entry structure object of the acceleration sensor. */ -struct HdfDriverEntry g_sensorAccelDevEntry = { - .moduleVersion = 1, /* Version of the acceleration sensor module */ - .moduleName = "HDF_SENSOR_ACCEL", /* Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file. */ - .Bind = BindAccelDriver, /* Binding function of the acceleration sensor */ - .Init = InitAccelDriver, /* Initialization function of the acceleration sensor */ - .Release = ReleaseAccelDriver, /* Resource release function of the acceleration sensor */ -}; - -/* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind function first and then the Init function. If the Init function fails to be called, the HDF will call Release to release the driver resource and exit. -HDF_INIT(g_sensorAccelDevEntry); -``` - -- Acceleration sensor configuration - -The acceleration sensor model uses the HCS as the configuration source code. For details about the HCS configuration fields, see [Driver Configuration Management](driver-hdf-manage.md). - -``` -/* HCS configuration of the acceleration sensor device */ -device_sensor_accel :: device { - device0 :: deviceNode { - policy = 1; /* Policy for providing the driver service */ - priority = 105; /* Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random. */ - preload = 2; /* Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. */ - permission = 0664; /* Permission for the driver to create device nodes */ - moduleName = "HDF_SENSOR_ACCEL"; /* Driver name. The value must be the same as that of moduleName in the driver entry structure. */ - serviceName = "sensor_accel"; /* Name of the service provided by the driver. The name must be unique. */ - deviceMatchAttr = "hdf_sensor_accel_driver"; /* Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. */ - } -} -``` - -1. Initialize and deinitialize the acceleration sensor driver. - -- Initialization entry function **init** - -``` -/* Bind the service provided by the acceleration sensor driver to the HDF. */ -int32_t BindAccelDriver(struct HdfDeviceObject *device) -{ - CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); - - static struct IDeviceIoService service = { - .object = {0}, - .Dispatch = DispatchAccel, - }; - device->service = &service; - - return HDF_SUCCESS; -} -/* After detecting that the device is in position, call RegisterAccelChipOps to register the differentiation adaptation function. */ -int32_t RegisterAccelChipOps(struct AccelOpsCall *ops) -{ - struct AccelDrvData *drvData = NULL; - - CHECK_NULL_PTR_RETURN_VALUE(ops, HDF_ERR_INVALID_PARAM); - - drvData = AccelGetDrvData(); - drvData->ops.Init = ops->Init; - drvData->ops.ReadData = ops->ReadData; - return HDF_SUCCESS; -} -/* Hook the acceleration sensor driver normalization function. */ -static int32_t InitAccelOps(struct SensorDeviceInfo *deviceInfo) -{ - struct AccelDrvData *drvData = AccelGetDrvData(); - - (void)memset_s((void *)deviceInfo, sizeof(*deviceInfo), 0, sizeof(*deviceInfo)); - deviceInfo->ops.GetInfo = SetAccelInfo; - deviceInfo->ops.Enable = SetAccelEnable; - deviceInfo->ops.Disable = SetAccelDisable; - deviceInfo->ops.SetBatch = SetAccelBatch; - deviceInfo->ops.SetMode = SetAccelMode; - deviceInfo->ops.SetOption = SetAccelOption; - - if (memcpy_s(&deviceInfo->sensorInfo, sizeof(deviceInfo->sensorInfo), - &drvData->accelCfg->sensorInfo, sizeof(drvData->accelCfg->sensorInfo)) != EOK) { - HDF_LOGE("%s: copy sensor info failed", __func__); - return HDF_FAILURE; - } - /* The sensor type ID can be configured in the HCS configuration file or here. */ - drvData->accelCfg->sensorInfo.sensorTypeId = SENSOR_TAG_ACCELEROMETER; - drvData->accelCfg->sensorInfo.sensorId = SENSOR_TAG_ACCELEROMETER; - - return HDF_SUCCESS; -} -/* Initialize the sensor register. */ -static int32_t InitAccelAfterConfig(void) -{ - struct SensorDeviceInfo deviceInfo; - - if (InitAccelConfig() != HDF_SUCCESS) { - HDF_LOGE("%s: init accel config failed", __func__); - return HDF_FAILURE; - } - - if (InitAccelOps(&deviceInfo) != HDF_SUCCESS) { - HDF_LOGE("%s: init accel ops failed", __func__); - return HDF_FAILURE; - } - - if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) { - HDF_LOGE("%s: add accel device failed", __func__); - return HDF_FAILURE; - } - - return HDF_SUCCESS; -} -/* Call the device detection function to hook the differentiated device function. */ -static int32_t DetectAccelChip(void) -{ - int32_t num; - int32_t ret; - int32_t loop; - struct AccelDrvData *drvData = AccelGetDrvData(); - CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); - - num = sizeof(g_accelDetectIfList) / sizeof(g_accelDetectIfList[0]); - for (loop = 0; loop < num; ++loop) { - if (g_accelDetectIfList[loop].DetectChip != NULL) { - ret = g_accelDetectIfList[loop].DetectChip(drvData->accelCfg); - if (ret == HDF_SUCCESS) { - drvData->detectFlag = true; - break; - } - } - } - - if (loop == num) { - HDF_LOGE("%s: detect accel device failed", __func__); - drvData->detectFlag = false; - return HDF_FAILURE; - } - return HDF_SUCCESS; -} -/* The entry function of the acceleration sensor driver is used to initialize the structure object of the sensor private data, allocate space for the HCS data configuration object of the sensor, invoke the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create the sensor data reporting timer, implement the sensor normalization API, and register the sensor device. */ -int32_t InitAccelDriver(struct HdfDeviceObject *device) -{ - /* Obtain the private data structure object of the sensor. */ - struct AccelDrvData *drvData = AccelGetDrvData(); - - /* When detecting sensors of the same type from different vendors, the function checks whether this type of sensors is in position. If yes, it no longer detects the other sensors of this type and directly returns the result. */ - if (drvData->detectFlag) { - HDF_LOGE("%s: accel sensor have detected", __func__); - return HDF_SUCCESS; - } - - CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); - /* Allocate space for the private data structure objects for storing sensor data configurations. The allocated space needs to be released when the driver is released. */ - drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*cfg)); - if (drvData->accelCfg == NULL) { - HDF_LOGE("%s: malloc sensor config data failed", __func__); - return HDF_FAILURE; - } +# Sensor - drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0]; - /* Initializing the sensor configuration data aims to parse the configuration information of the sensor communication bus, basic sensor information, sensor attributes, whether the sensor is in position, and register group information. */ - if (GetSensorBaseConfigData(device->property, drvData->accelCfg) != HDF_SUCCESS) { - HDF_LOGE("%s: get sensor base config failed", __func__); - goto Base_CONFIG_EXIT; - } - - if (DetectAccelChip() != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor detect device no exist", __func__); - goto DETECT_CHIP_EXIT; - } - drvData->detectFlag = true; - if (ParseSensorRegConfig(drvData->accelCfg) != HDF_SUCCESS) { - HDF_LOGE("%s: detect sensor device failed", __func__); - goto REG_CONFIG_EXIT; - } - - if (InitAccelAfterConfig() != HDF_SUCCESS) { - HDF_LOGE("%s: init accel after config failed", __func__); - goto INIT_EXIT; - } - HDF_LOGI("%s: init accel driver success", __func__); - return HDF_SUCCESS; - -INIT_EXIT: - DestroySensorThread(&drvData->thread, &drvData->threadStatus); - (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); -REG_CONFIG_EXIT: - ReleaseSensorAllRegConfig(drvData->accelCfg); - (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); -DETECT_CHIP_EXIT: - drvData->detectFlag = false; -BASE_CONFIG_EXIT: - drvData->accelCfg->root = NULL; - drvData->accelCfg->regCfgGroup = NULL; - OsalMemFree(drvData->accelCfg); - drvData->accelCfg = NULL; - return HDF_FAILURE; -} +## Overview -/* Release the resources allocated during driver initialization. */ -void ReleaseAccelDriver(struct HdfDeviceObject *device) -{ - (void)device; - struct AccelDrvData *drvData = NULL; - - drvData = AccelGetDrvData(); - (void)DestroySensorThread(&drvData->thread, &drvData->threadStatus); - (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); - drvData->detectFlag = false; - - if (drvData->accelCfg != NULL) { - drvData->accelCfg->root = NULL; - drvData->accelCfg->regCfgGroup = NULL; - ReleaseSensorAllRegConfig(drvData->accelCfg); - (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); - OsalMemFree(drvData->accelCfg); - drvData->accelCfg = NULL; - } +### Introduction - drvData->initStatus = false; -} -``` - -1. Configure the acceleration sensor register group. +The sensor driver model masks the sensor hardware differences and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor options. The model is developed on the Hardware Driver Foundation (HDF), Operating System Abstraction Layer (OSAL), and platform driver interfaces (such as the I2C, SPI, and UART buses). It provides functionalities such as cross-OS migration and differentiated device configurations. The figure below shows the architecture of the sensor driver model. -You only need to configure the acceleration sensor data according to the template. Template configuration parsing has been implemented via the **InitSensorConfigData** function and only needs to be called during initialization. If new configuration items are added, you need to modify this function accordingly. +**Figure 1** Sensor driver model +![Sensor driver model](figures/sensor_driver_model.png) -``` -Acceleration sensor data configuration template (accel_config.hcs) -root { - sensorAccelConfig { - accelChipConfig { - /* Sensor information template */ - template sensorInfo { - sensorName = "accelerometer"; /* Acceleration sensor name. The value contains a maximum of 16 bytes. */ - vendorName = "borsh_bmi160"; /* Sensor vendor name. The value contains a maximum of 16 bytes. */ - firmwareVersion = "1.0"; /* Sensor firmware version. The default value is 1.0. The value contains a maximum of 16 bytes. */ - hardwareVersion = "1.0"; /* Sensor hardware version. The default value is 1.0. The value contains a maximum of 16 bytes. */ - sensorTypeId = 1; /* Sensor type ID. For details, see SensorTypeTag. */ - sensorId = 1; /* Sensor ID, which is defined by the sensor driver developer. The SensorTypeTag enums are recommended. */ - maxRange = 8; /* Maximum measurement range of the sensor. Set this parameter based on your business requirements. */ - precision = 0; /* Sensor accuracy, which is used together with sensor data reporting. For details, see SensorEvents. */ - power = 230; /* Power consumption of the sensor */ - } - /* Template of the bus type and configuration information used by the sensor */ - template sensorBusConfig { - busType = 0; /* 0:i2c 1:spi */ - busNum = 6; /* Device ID allocated to the sensor on the chip */ - busAddr = 0; /* Address allocated to the sensor on the chip */ - regWidth = 1; /* Width of the sensor register address */ - regBigEndian = 0; /* Endian mode of the sensor register */ - } - /* Sensor attribute template */ - template sensorAttr { - chipName = ""; /* Sensor chip name */ - chipIdRegister = 0xf; /* Address of the register detecting whether the sensor is in position */ - chipIdValue = 0xd1; /* Value of the register detecting whether the sensor is in position */ - } - } - } -} +### Basic Concepts -/* You can modify the template configuration based on the differences of sensor devices. If no modification is made, the default template configuration is used. */ -root { - sensorAccelConfig { - accel_bmi160_chip_config : accelChipConfig { - match_attr = "hdf_sensor_accel_driver"; /* The value must be the same as the match_attr field configured for the acceleration sensor. */ - accelInfo :: sensorInfo { - vendorName = "borsh_bmi160"; - sensorTypeId = 1; - sensorId = 1; - } - accelBusConfig :: sensorBusConfig { - busType = 0; /* I2C communication mode */ - busNum = 6; - busAddr = 0x68; - regWidth = 1; /* 1-byte bit width */ - } - accelAttr :: sensorAttr { - chipName = "bmi160"; - chipIdRegister = 0x00; - chipIdValue = 0xd1; - } - accelRegConfig { - /* regAddr: Register address - value: Register value - mask: Mask of the register value - len: Length (in bytes) of the register value - delay: Register delay (in milliseconds) - opsType: Operation type. The options can be 0 (no operation), 1 (read), 2 (write), 3 (read and check), and 4 (bit update). - calType: Calculation type. The options can be 0 (none), 1 (write), 2 (negate), 3 (XOR) 4, (left shift), and 5 (right shift). - shiftNum: Number of shifts - debug: Debugging switch. The value can be 0 (disabled) or 1 (enabled). - save: Data saving switch. The value can be 0 (not save data) or 1 (save data). - */ - /* Groups of sensor register operations. Registers can be configured in sequence based on the groups. */ - /* Register address, register value, mask of the register value, data length of the register value, register delay, operation type, calculation type, number of shifts, debugging switch, data saving switch */ - /* Initialize the register groups. */ - initSeqConfig = [ - 0x7e, 0xb6, 0xff, 1, 5, 2, 0, 0, 0, 0, - 0x7e, 0x10, 0xff, 1, 5, 2, 0, 0, 0, 0 - ]; - /* Enable the register groups. */ - enableSeqConfig = [ - 0x7e, 0x11, 0xff, 1, 5, 2, 0, 0, 0, 0, - 0x41, 0x03, 0xff, 1, 0, 2, 0, 0, 0, 0, - 0x40, 0x08, 0xff, 1, 0, 2, 0, 0, 0, 0 - ]; - /* Disable the register groups. */ - disableSeqConfig = [ - 0x7e, 0x10, 0xff, 1, 5, 2, 0, 0, 0, 0 - ]; - } - } - } -} -``` +Currently, sensors are classified into medical sensors and traditional sensors by sensor ID. -1. Implement APIs for acceleration sensor driver operations. +- The IDs of medical sensors range from 128 to 160. -You need to implement normalized APIs based on sensor types. +- The IDs of traditional sensors are out of the range of 128 to 160. -``` -/* Leave a function empty if it is not used. */ -static int32_t SetAccelInfo(struct SensorBasicInfo *info) -{ - (void)info; +### Working Principles - return HDF_ERR_NOT_SUPPORT; -} -/* Deliver the configuration of enabling the register groups. */ -static int32_t SetAccelEnable(void) -{ - int32_t ret; - struct AccelDrvData *drvData = AccelGetDrvData(); - - CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); - ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor disable config failed", __func__); - return HDF_FAILURE; - } +Based on the loading and running process (shown below) of the sensor driver model, the relationships between key modules in the model and associated modules are clearly defined. - drvData->threadStatus = SENSOR_THREAD_RUNNING; +**Figure 2** How sensor driver works - return HDF_SUCCESS; -} -/* Deliver the configuration of disabling the register groups. */ -static int32_t SetAccelDisable(void) -{ - int32_t ret; - struct AccelDrvData *drvData = AccelGetDrvData(); +![How sensor driver works](figures/sensor_working.png) - CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); +The following uses the acceleration sensor driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process. - ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor disable config failed", __func__); - return HDF_FAILURE; - } +1. The sensor host reads the sensor management configuration from the Sensor Host node of the device_info HCS (sensor device information HCS). +2. The sensor host parses the sensor management configuration from the HCB database and associates the corresponding sensor driver. +3. The sensor host loads and initializes the sensor manager driver. +4. The sensor manager driver publishes the sensor hardware driver interfaces (HDIs). +5. The sensor host reads the acceleration sensor driver configuration from the Sensor Host node of the device_info HCS. +6. The sensor host loads the acceleration sensor abstract driver and calls the initialization interface to allocate the sensor driver resources and create the data processing queue. +7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the accel_xxx_config HCS (sensor private configuration HCS). +8. The acceleration sensor chipset driver calls the common configuration parsing interface to parse the sensor attributes and registers. +9. The chipset driver detects sensors, allocates configuration resources to the acceleration sensor, and registers the acceleration sensor chipset interfaces. +10. Upon successful sensor detection, the chipset driver instructs the abstract driver to register the acceleration sensor to the sensor manager driver. - drvData->threadStatus = SENSOR_THREAD_STOPPED; +## Development Guidelines - return HDF_SUCCESS; -} -/* Set the sampling interval and data reporting interval of the sensor. */ -static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval) -{ - (void)interval; +### When to Use - struct AccelDrvData *drvData = AccelGetDrvData(); - drvData->interval = samplingInterval; +- Data provided by the gravity and gyroscope sensors denotes the tilt and rotation of the device, which helps your application improve user experience in games. +- Data provided by the proximity sensor denotes the distance between the device and a visible object, which enables the device to automatically turn on or off its screen accordingly to prevent accidental touch on the screen. For example, when the proximity sensor detects the user face approaches the earpiece during a call, it triggers backlight of the screen to be turned off. This can further reduce power consumption. +- Data provided by the barometric pressure sensor helps your application accurately determine the altitude of the device. +- Data provided by the ambient light sensor helps your device automatically adjust its backlight. +- Data provided by the Hall effect sensor implements the smart cover mode of your device. When the smart cover is closed, a small window is opened on the phone to reduce power consumption. - return HDF_SUCCESS; -} -/* Set the data reporting mode of the sensor. Currently, the real-time mode is supported. */ -static int32_t SetAccelMode(int32_t mode) -{ - return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE; -} -/* Set the sensor options. */ -static int32_t SetAccelOption(uint32_t option) -{ - (void)option; - return HDF_ERR_NOT_SUPPORT; -} -``` +### Available APIs -- Differentiated processing APIs - - ``` - /* If a device is detected, register the differentiated processing function to the accel driver model. */ - int32_t DetectAccelBim160Chip(struct SensorCfgData *data) - { - int32_t ret; - struct AccelOpsCall ops; - CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); - - if (strcmp(ACCEL_CHIP_NAME_BMI160, data->sensorAttr.chipName) != 0) { - return HDF_SUCCESS; - } - ret = InitAccelPreConfig(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: init BMI160 bus mux config", __func__); - return HDF_FAILURE; - } - if (DetectSensorDevice(data) != HDF_SUCCESS) { - return HDF_FAILURE; - } - - /* Differentiated processing function */ - ops.Init = InitBmi160; - ops.ReadData = ReadBmi160Data; - ret = RegisterAccelChipOps(&ops); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: register BMI160 accel failed", __func__); - (void)ReleaseSensorBusHandle(&data->busCfg); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - /* Initialization processing function */ - static int32_t InitBmi160(struct SensorCfgData *data) - { - int32_t ret; - - CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); - ret = SetSensorRegCfgArray(&data->busCfg, data->regCfgGroup[SENSOR_INIT_GROUP]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: bmi160 sensor init config failed", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - /* Data processing function */ - int32_t ReadBmi160Data(struct SensorCfgData *data) - { - int32_t ret; - struct AccelData rawData = { 0, 0, 0 }; - int32_t tmp[ACCEL_AXIS_NUM]; - struct SensorReportEvent event; - - (void)memset_s(&event, sizeof(event), 0, sizeof(event)); - - ret = ReadBmi160RawData(data, &rawData, &event.timestamp); - if (ret != HDF_SUCCESS) { - return HDF_FAILURE; - } - - event.sensorId = SENSOR_TAG_ACCELEROMETER; - event.option = 0; - event.mode = SENSOR_WORK_MODE_REALTIME; - - rawData.x = rawData.x * BMI160_ACC_SENSITIVITY_2G; - rawData.y = rawData.y * BMI160_ACC_SENSITIVITY_2G; - rawData.z = rawData.z * BMI160_ACC_SENSITIVITY_2G; - - tmp[ACCEL_X_AXIS] = (rawData.x * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - tmp[ACCEL_Y_AXIS] = (rawData.y * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - tmp[ACCEL_Z_AXIS] = (rawData.z * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - - event.dataLen = sizeof(tmp); - event.data = (uint8_t *)&tmp; - ret = ReportSensorEvent(&event); - return ret; - } - ``` - -- Data processing function - -Create a sensor timer to periodically sample data based on the configured sampling interval and report the data to the data subscriber. - -``` -/* Scheduled working thread of the sensor */ -static int32_t ReadAccelDataThreadWorker(void *arg) -{ - (void)arg; - int64_t interval; - struct AccelDrvData *drvData = AccelGetDrvData(); - - drvData->threadStatus = SENSOR_THREAD_START; - while (true) { - if (drvData->threadStatus == SENSOR_THREAD_RUNNING) { - if (drvData->ops.ReadData != NULL) { - (void)drvData->ops.ReadData(drvData->accelCfg); - } - interval = OsalDivS64(drvData->interval, (SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT)); - OsalMSleep(interval); - } else if (drvData->threadStatus == SENSOR_THREAD_DESTROY) { - break; - } else { - OsalMSleep(ACC_DEFAULT_SAMPLING_200_MS / SENSOR_CONVERT_UNIT / SENSOR_CONVERT_UNIT); - } - - if ((!drvData->initStatus) || (drvData->interval < 0) || drvData->threadStatus != SENSOR_THREAD_RUNNING) { - continue; - } - } - - return HDF_SUCCESS; -} -/* Create a sensor timer and initialize the sensor device. */ -static int32_t InitAccelConfig(void) -{ - int32_t ret; - struct AccelDrvData *drvData = AccelGetDrvData(); - - if (drvData->threadStatus != SENSOR_THREAD_NONE && drvData->threadStatus != SENSOR_THREAD_DESTROY) { - HDF_LOGE("%s: accel thread have created", __func__); - return HDF_SUCCESS; - } - - ret = CreateSensorThread(&drvData->thread, ReadAccelDataThreadWorker, "hdf_sensor_accel", drvData); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel create thread failed", __func__); - drvData->threadStatus = SENSOR_THREAD_NONE; - return HDF_FAILURE; - } - - CHECK_NULL_PTR_RETURN_VALUE(drvData->ops.Init, HDF_ERR_INVALID_PARAM); - - ret = drvData->ops.Init(drvData->accelCfg); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel create thread failed", __func__); - drvData->threadStatus = SENSOR_THREAD_NONE; - return HDF_FAILURE; - } - drvData->initStatus = true; - return HDF_SUCCESS; -} -``` - -- Major data structures - -``` -/* Sensor conversion units */ -#define SENSOR_CONVERT_UNIT 1000 -#define SENSOR_1K_UNIT 1024 -/* Sensitivity conversion value of the sensor with a 2g measurement range */ -#define BMI160_ACC_SENSITIVITY_2G 61 -/* Address of the sensor data sampling register */ -#define BMI160_ACCEL_X_LSB_ADDR 0X12 -#define BMI160_ACCEL_X_MSB_ADDR 0X13 -#define BMI160_ACCEL_Y_LSB_ADDR 0X14 -#define BMI160_ACCEL_Y_MSB_ADDR 0X15 -#define BMI160_ACCEL_Z_LSB_ADDR 0X16 -#define BMI160_ACCEL_Z_MSB_ADDR 0X17 -/* Data dimension of the sensor */ -enum AccelAxisNum { - ACCEL_X_AXIS = 0, - ACCEL_Y_AXIS = 1, - ACCEL_Z_AXIS = 2, - ACCEL_AXIS_NUM = 3, -}; -/* Each dimension of the sensor */ -struct AccelData { - int32_t x; - int32_t y; - int32_t z; -}; -/* Private data structure of the sensor */ -struct AccelDrvData { - bool detectFlag; - uint8_t threadStatus; - uint8_t initStatus; - int64_t interval; - struct SensorCfgData *accelCfg; - struct OsalThread thread; - struct AccelOpsCall ops; -}; -/* Differentiation adaptation function */ -struct AccelOpsCall { - int32_t (*Init)(struct SensorCfgData *data); - int32_t (*ReadData)(struct SensorCfgData *data); -}; -``` - -## Test Guidelines +The sensor driver model offers the following APIs: -After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. The developer self-test platform is used as the test environment. +- Sensor HDIs, for easier sensor service development +- Sensor driver model capability interfaces + - Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors + - Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors +- Interfaces to be implemented by developers: Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, developers need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development. + +The sensor driver model provides APIs for the hardware service to make sensor service development easier. See the table below. + +**Table 1** APIs for the members in the PinCntlrMethod structure + +| API| Description| +| ----- | -------- | +| int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | Obtains information about all registered sensors in the system. The sensor information includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum range, accuracy, and power consumption.| +| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.| +| int32_t Disable(int32_t sensorId) | Disables a sensor.| +| int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.| +| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.| +| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.| +| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.| +| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.| + + + +The sensor driver model provides driver development APIs that do not require further implementation. See the table below. + + **Table 2** Sensor driver development APIs that do not need to be implemented by driver developers + +| API| Description| +| ----- | -------- | +| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | Adds a sensor of the current type to the sensor management module.| +| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | Deletes a sensor from the sensor management module.| +| int32_t ReportSensorEvent(const struct SensorReportEvent *events) | Reports data of a specified sensor type.| +| int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen) | Reads sensor configuration data from the sensor register based on the bus configuration.| +| int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len) | Writes sensor configuration data to the sensor register based on the bus configuration.| +| int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group); | Sets the sensor register group configuration based on the sensor bus type.| +| int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config) | Obtains basic configuration information such as sensor, bus, and attribute configurations based on the device information HCS configuration, and initializes the basic configuration data structure.| +| int32_t ParseSensorRegConfig(struct SensorCfgData *config) | Parses the register group information based on the device information HCS configuration and initializes the configuration data structure.| +| void ReleaseSensorAllRegConfig(struct SensorCfgData *config) | Releases the resources allocated to the sensor configuration data structure.| +| int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) | Obtains the sensor bus handle information.| +| int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg) | Releases the sensor bus handle information.| + + + +The sensor driver model also provides certain driver development APIs that need to be implemented by driver developers. See the table below. + +**Table 3** Driver development APIs that need to be implemented by driver developers + +| API| Description| +| ----- | -------- | +| int32_t init(void) | Initializes the sensor device configuration after a sensor is detected.| +| int32_t Enable(void) | Enables the current sensor by delivering the register configuration in the enabling operation group based on the device information HCS configuration.| +| int32_t Disable(void) | Disables the current sensor by delivering the register configuration in the disabling operation group based on the device information HCS configuration.| +| int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval) | Sets the processing time of the data reporting thread for the current sensor based on the sampling interval and data reporting interval.| +| int32_t SetMode(int32_t mode) | Sets the data reporting mode of the current sensor device.| +| int32_t SetOption(uint32_t option) | Sets the register configuration such as the range and accuracy based on sensor options.| +| void ReadSensorData(void) | Reads sensor data.| + + +For details about the interface implementation, see [How to Develop](#section7893102915819). + +### How to Develop +1. Develop the acceleration sensor abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. + + - Implement the entry function for the acceleration sensor. + + ```c + /* Register the entry structure object of the acceleration sensor. */ + struct HdfDriverEntry g_sensorAccelDevEntry = { + .moduleVersion = 1, // Version of the acceleration sensor module. + .moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file. + .Bind = BindAccelDriver, // Function for binding an acceleration sensor. + .Init = InitAccelDriver, // Function for initializing an acceleration sensor. + .Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources. + }; + + /* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind function first and then the Init function. If the Init function fails to be called, the HDF will call Release to release the driver resource and exit the sensor driver model. */ + HDF_INIT(g_sensorAccelDevEntry); + ``` + + - Implement interfaces for acceleration sensor driver operations. + + ```c + /* Bind the service provided by the acceleration sensor driver to the HDF. */ + int32_t AccelBindDriver(struct HdfDeviceObject *device) + { + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + struct AccelDrvData *drvData = (struct AccelDrvData *)OsalMemCalloc(sizeof(*drvData)); + if (drvData == NULL) { + HDF_LOGE("%s: Malloc accel drv data fail!", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + drvData->ioService.Dispatch = DispatchAccel; + drvData->device = device; + device->service = &drvData->ioService; + g_accelDrvData = drvData; + return HDF_SUCCESS; + } + + /* Register the normalization functions of the acceleration sensor driver. */ + static int32_t InitAccelOps(struct SensorCfgData *config, struct SensorDeviceInfo *deviceInfo) + { + CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM); + + deviceInfo->ops.Enable = SetAccelEnable; + deviceInfo->ops.Disable = SetAccelDisable; + deviceInfo->ops.SetBatch = SetAccelBatch; + deviceInfo->ops.SetMode = SetAccelMode; + deviceInfo->ops.SetOption = SetAccelOption; + + if (memcpy_s(&deviceInfo->sensorInfo, sizeof(deviceInfo->sensorInfo), + &config->sensorInfo, sizeof(config->sensorInfo)) != EOK) { + HDF_LOGE("%s: Copy sensor info failed", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + /* Provide the initialization interface for the chipset driver to parse the basic acceleration sensor configuration (acceleration information, bus configuration, and sensor detection register configuration), detect sensors, and parse sensor registers. */ + static int32_t InitAccelAfterDetected(struct SensorCfgData *config) + { + struct SensorDeviceInfo deviceInfo; + CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM); + /* Initialize the acceleration sensor function. */ + if (InitAccelOps(config, &deviceInfo) != HDF_SUCCESS) { + HDF_LOGE("%s: Init accel ops failed", __func__); + return HDF_FAILURE; + } + /* Register the acceleration sensor with the sensor management module. */ + if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) { + HDF_LOGE("%s: Add accel device failed", __func__); + return HDF_FAILURE; + } + /* Parse the sensor register. */ + if (ParseSensorRegConfig(config) != HDF_SUCCESS) { + HDF_LOGE("%s: Parse sensor register failed", __func__); + (void)DeleteSensorDevice(&config->sensorInfo); + ReleaseSensorAllRegConfig(config); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + struct SensorCfgData *AccelCreateCfgData(const struct DeviceResourceNode *node) + { + ...... + /* Continue the next detection if the sensor is not detected. */ + if (drvData->detectFlag) { + HDF_LOGE("%s: Accel sensor have detected", __func__); + return NULL; + } + if (drvData->accelCfg == NULL) { + HDF_LOGE("%s: Accel accelCfg pointer NULL", __func__); + return NULL; + } + /* Parse the basic sensor configuration. */ + if (GetSensorBaseConfigData(node, drvData->accelCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: Get sensor base config failed", __func__); + goto BASE_CONFIG_EXIT; + } + /* Continue the next detection if the sensor is not detected. */ + if (DetectSensorDevice(drvData->accelCfg) != HDF_SUCCESS) { + HDF_LOGI("%s: Accel sensor detect device no exist", __func__); + drvData->detectFlag = false; + goto BASE_CONFIG_EXIT; + } + drvData->detectFlag = true; + /* Parse the sensor register. */ + if (InitAccelAfterDetected(drvData->accelCfg) != HDF_SUCCESS) { + HDF_LOGE("%s: Accel sensor detect device no exist", __func__); + goto INIT_EXIT; + } + return drvData->accelCfg; + ...... + } + /* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a sensor data reporting timer, register the sensor normalization APIs, and register the sensor device. */ + int32_t AccelInitDriver(struct HdfDeviceObject *device) + { + ...... + /* Initialize work queue resources. */ + if (InitAccelData(drvData) != HDF_SUCCESS) { + HDF_LOGE("%s: Init accel config failed", __func__); + return HDF_FAILURE; + } + /* Allocate acceleration configuration resources. */ + drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*drvData->accelCfg)); + if (drvData->accelCfg == NULL) { + HDF_LOGE("%s: Malloc accel config data failed", __func__); + return HDF_FAILURE; + } + /* Register the register group information. */ + drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0]; + ...... + return HDF_SUCCESS; + } + /* Release the resources allocated during driver initialization. */ + void AccelReleaseDriver(struct HdfDeviceObject *device) + { + CHECK_NULL_PTR_RETURN(device); + struct AccelDrvData *drvData = (struct AccelDrvData *)device->service; + CHECK_NULL_PTR_RETURN(drvData); + /* Release the resources if the sensor is in position. */ + if (drvData->detectFlag) { + AccelReleaseCfgData(drvData->accelCfg); + } + OsalMemFree(drvData->accelCfg); + drvData->accelCfg = NULL; + /* Destroy the work queue resource if the sensor is in position. */ + HdfWorkDestroy(&drvData->accelWork); + HdfWorkQueueDestroy(&drvData->accelWorkQueue); + OsalMemFree(drvData); + } + ``` + +2. Configure the device information about the acceleration sensor driver. + + The acceleration sensor model uses the HCS as the configuration source code. For details about the HCS configuration fields, see [Driver Configuration Management](driver-hdf-manage.md). + + ``` + /* Device information HCS configuration of the acceleration sensor. */ + device_sensor_accel :: device { + device0 :: deviceNode { + policy = 1; // Policy for publishing the driver service. + priority = 110; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random. + preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. + permission = 0664; // Permission for the driver to create a device node. + moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure. + serviceName = "sensor_accel"; // Name of the service provided by the driver. The name must be unique. + deviceMatchAttr = "hdf_sensor_accel_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. + } + } + ``` + +3. Develop the internal interfaces of the acceleration sensor abstract driver. Specifically, implement the **Enable**, **Disable**, **SetBatch**, **SetMode**, **SetOption**, **AccelCreateCfgData**, **AccelReleaseCfgData**, and **AccelRegisterChipOps** functions. + + ```c + /* Leave a function empty if it is not used. */ + static int32_t SetAccelInfo(struct SensorBasicInfo *info) + { + (void)info; + + return HDF_ERR_NOT_SUPPORT; + } + /* Deliver the configuration of enabling the register groups. */ + static int32_t SetAccelEnable(void) + { + int32_t ret; + struct AccelDrvData *drvData = AccelGetDrvData(); + + CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); + + if (drvData->enable) { + HDF_LOGE("%s: Accel sensor is enabled", __func__); + return HDF_SUCCESS; + } + + ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Accel sensor enable config failed", __func__); + return ret; + } + + ret = OsalTimerCreate(&drvData->accelTimer, SENSOR_TIMER_MIN_TIME, AccelTimerEntry, (uintptr_t)drvData); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Accel create timer failed[%d]", __func__, ret); + return ret; + } + + ret = OsalTimerStartLoop(&drvData->accelTimer); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Accel start timer failed[%d]", __func__, ret); + return ret; + } + drvData->enable = true; + + return HDF_SUCCESS; + } + /* Deliver the configuration of disabling the register groups. */ + static int32_t SetAccelDisable(void) + { + int32_t ret; + struct AccelDrvData *drvData = AccelGetDrvData(); + + CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM); + CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); + + if (!drvData->enable) { + HDF_LOGE("%s: Accel sensor had disable", __func__); + return HDF_SUCCESS; + } + + ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Accel sensor disable config failed", __func__); + return ret; + } + + ret = OsalTimerDelete(&drvData->accelTimer); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Accel delete timer failed", __func__); + return ret; + } + drvData->enable = false; + + return HDF_SUCCESS; + } + /* Set the sampling interval and data reporting interval of the sensor. */ + static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval) + { + (void)interval; + + struct AccelDrvData *drvData = NULL; + + drvData = AccelGetDrvData(); + CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM); + + drvData->interval = samplingInterval; + + return HDF_SUCCESS; + } + /* Set the data reporting mode of the sensor. Currently, the real-time mode is supported. */ + static int32_t SetAccelMode(int32_t mode) + { + return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE; + } + + static int32_t SetAccelOption(uint32_t option) + { + (void)option; + return HDF_SUCCESS; + } + /* Set the sensor options. */ + static int32_t SetAccelOption(uint32_t option) + { + (void)option; + return HDF_ERR_NOT_SUPPORT; + } + ``` + +4. Develop the acceleration sensor chipset driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. + + ```c + /* Message interaction of the acceleration sensor chipset driver */ + static int32_t DispatchBMI160(struct HdfDeviceIoClient *client, + int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) + { + (void)client; + (void)cmd; + (void)data; + (void)reply; + + return HDF_SUCCESS; + } + /* Bind the service provided by the acceleration sensor chipset driver to the HDF. */ + int32_t Bmi160BindDriver(struct HdfDeviceObject *device) + { + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + + struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)OsalMemCalloc(sizeof(*drvData)); + if (drvData == NULL) { + HDF_LOGE("%s: Malloc Bmi160 drv data fail", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + drvData->ioService.Dispatch = DispatchBMI160; + drvData->device = device; + device->service = &drvData->ioService; + g_bmi160DrvData = drvData; + + return HDF_SUCCESS; + } + /* Initialize the acceleration sensor chipset driver. */ + int32_t Bmi160InitDriver(struct HdfDeviceObject *device) + { + int32_t ret; + struct AccelOpsCall ops; + + CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); + struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)device->service; + CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM); + + ret = InitAccelPreConfig(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Init BMI160 bus mux config", __func__); + return HDF_FAILURE; + } + + drvData->sensorCfg = AccelCreateCfgData(device->property); + if (drvData->sensorCfg == NULL || drvData->sensorCfg->root == NULL) { + HDF_LOGD("%s: Creating accelcfg failed because detection failed", __func__); + return HDF_ERR_NOT_SUPPORT; + } + + ops.Init = NULL; + ops.ReadData = ReadBmi160Data; + ret = AccelRegisterChipOps(&ops); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Register BMI160 accel failed", __func__); + return HDF_FAILURE; + } + + ret = InitBmi160(drvData->sensorCfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: Init BMI160 accel failed", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + /* Release the resources allocated during driver initialization. */ + void Bmi160ReleaseDriver(struct HdfDeviceObject *device) + { + ...... + if (drvData->sensorCfg != NULL) { + AccelReleaseCfgData(drvData->sensorCfg); + drvData->sensorCfg = NULL; + } + OsalMemFree(drvData); + } + /*HdfDriverEntry object corresponding to the acceleration sensor chipset driver */ + struct HdfDriverEntry g_accelBmi160DevEntry = { + .moduleVersion = 1, + .moduleName = "HDF_SENSOR_ACCEL_BMI160", + .Bind = Bmi160BindDriver, + .Init = Bmi160InitDriver, + .Release = Bmi160ReleaseDriver, + }; + HDF_INIT(g_accelBmi160DevEntry); + ``` + +5. Implement the **ReadData** function of the acceleration sensor chipset driver. + + ```c + int32_t ReadBmi160Data(struct SensorCfgData *data) + { + int32_t ret; + struct AccelData rawData = { 0, 0, 0 }; + int32_t tmp[ACCEL_AXIS_NUM]; + struct SensorReportEvent event; + (void)memset_s(&event, sizeof(event), 0, sizeof(event)); + ret = ReadBmi160RawData(data, &rawData, &event.timestamp); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: BMI160 read raw data failed", __func__); + return HDF_FAILURE; + } + event.sensorId = SENSOR_TAG_ACCELEROMETER; + event.option = 0; + event.mode = SENSOR_WORK_MODE_REALTIME; + ...... + ret = ReportSensorEvent(&event); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: BMI160 report data failed", __func__); + } + return ret; + } + ``` + +>![](../public_sys-resources/icon-note.gif) **NOTE** +> +>- The sensor driver model provides certain APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, common configuration, and configuration parsing capabilities. For details about them, see [Table 2](#table1156812588320). +> +>- You need to implement the following functions: certain sensor operation interfaces (listed in [Table 3](#table1083014911336)) and sensor chipset HCS configuration. +> - You also need to verify basic driver functions. + +### Commissioning and Verifying + +After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. Use the developer self-test platform as the test environment. ``` -/* Specify whether to report sensor data. */ -static int32_t g_sensorDataFlag = 0; -/* Retain the address of the sensor interface instance. */ -static const struct SensorInterface *g_sensorDev = nullptr; +static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data. +static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address. /* Register the data reporting function. */ static int SensorTestDataCallback(struct SensorEvents *event) @@ -877,14 +559,14 @@ void HdfSensorTest::TearDownTestCase() /* Verify the sensor driver. */ HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) { - int32_t sensorInterval = 1000000000; /* Data sampling interval, in nanoseconds */ - int32_t pollTime = 5; /* Data sampling duration, in seconds */ - int32_t accelSensorId = 1; /* Acceleration sensor type ID, which is 1 */ + int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds. + int32_t pollTime = 5; // Data sampling duration, in seconds. + int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1. int32_t count = 0; int ret; struct SensorInformation *sensorInfo = nullptr; - ret = g_sensorDev->Register(SensorTestDataCallback) + ret = g_sensorDev->Register(0, TraditionSensorTestDataCallback) EXPECT_EQ(SENSOR_NULL_PTR, ret); ret = g_sensorDev->GetAllSensors(&sensorInfo, &count); @@ -911,8 +593,7 @@ HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) g_sensorDataFlag = 0; EXPECT_EQ(0, ret); - ret = g_sensorDev->Unregister(); + ret = g_sensorDev->Unregister(0, TraditionSensorTestDataCallback); EXPECT_EQ(0, ret); } ``` - diff --git a/en/device-dev/driver/driver-peripherals-vibrator-des.md b/en/device-dev/driver/driver-peripherals-vibrator-des.md new file mode 100644 index 0000000000000000000000000000000000000000..9b38fe6b46925333724714a092d9ea9d5109cd70 --- /dev/null +++ b/en/device-dev/driver/driver-peripherals-vibrator-des.md @@ -0,0 +1,368 @@ +# Vibrator + +## Overview + +### Introduction + +Developed on the Hardware Driver Foundation (HDF), the vibrator driver model makes vibrator driver development easier. This model masks the interaction between the device driver and system, provides unified and stable driver interfaces for the hardware service layer, and offers open interfaces and interface parsing capabilities for driver developers. This document provides guidance for developing vibrator drivers and deploying vibrators in different OSs. The figure below shows the vibrator driver model. + +**Figure 1** Vibrator driver model + +![Vibrator driver model](figures/vibrator_driver_model.png) + +### Basic Concepts + +The system controls device vibration by invoking the vibrator. There are two vibration modes: + +- One-shot vibration + + The vibrator vibrates for a specified duration. + +- Periodic vibration + + The vibrator vibrates with a preset effect. For example, if the preset effect is "haptic.clock.timer" = [600, 600, 200, 600], the vibrator waits for 600 ms, vibrates for 600 ms, waits for 200 ms, and vibrates for 600 ms. + +### Working Principles + +Based on the loading and running process (shown below) of the vibrator driver model, the relationships between key modules in the model and associated modules are clearly defined. + +**Figure 2** How vibrator driver works + +![How vibrator driver works](figures/vibrator_working.png) + +The following uses the vibrator driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process. + +1. The vibrator host reads the vibrator management configuration from the Vibrator Host node of the device_info HCS (vibrator device information HCS). +2. The vibrator host parses the vibrator management configuration and associates it with the corresponding vibrator abstract driver. +3. The vibrator host reads the vibrator data configuration from the linear_vibrator_config HCS (vibrator private configuration HCS). +4. The vibrator host parses the vibrator data configuration and associates it with the corresponding vibrator haptic driver. +5. The vibrator proxy delivers an instruction to the vibrator stub. +6. The vibrator stub calls the vibrator controller. +7. The vibrator host initializes the vibrator abstract driver interfaces. +8. The vibrator haptic driver starts a thread to parse the vibrator haptic module. +9. The vibrator haptic driver calls the **Start** interface in the vibrator abstract driver. +10. The vibrator abstract driver calls the **Start** interface in the vibrator chipset driver. + +## Development Guidelines + +### When to Use + +You can set different vibration effects as needed, for example, customizing vibration effects with different intensities and durations for buttons on the device, and customizing one-shot or periodic vibration effects with different intensities and durations for alarm clocks and incoming calls. + +### Available APIs + +The vibrator driver model supports static HDF Configuration Source (HCS) configurations and dynamic parameter configurations. The vibrator hardware service calls the **StartOnce** interface to trigger continuous vibration and calls the **Start** interface to trigger vibration with a specified effect. The table below lists the APIs provided by the vibrator driver model for the hardware service layer. + +**Table 1** External APIs of the vibrator driver model + +| API | Description | +| -------------------------------------- | -------------------------------------------------------- | +| int32_t StartOnce(uint32_t duration) | Triggers vibration with a given **duration**. | +| int32_t Start(const char *effectType) | Triggers vibration with a given effect, which is specified by **effectType**.| +| int32_t Stop(enum VibratorMode mode) | Stops vibration. | + +### How to Develop + +The vibrator driver model provides stable interfaces for the upper-layer hardware service to trigger a one-shot vibration with a given duration, trigger vibration with a given effect, and stop vibration. The model implements functionalities such as cross-OS migration and differentiated configurations. To develop a vibrator, perform the following steps: + +1. Develop the vibrator abstract driver based on the driver entry. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions, configure resources, and parse HCS configurations. + + - Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If the **Init** function fails to be called, the HDF calls **Release** to release the driver resources and exit the vibrator driver model. The vibrator driver model uses the HCS as the configuration source code. For details about HCS fields, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md). The driver entry function is defined as follows: + + ```c + /* Register the entry structure object of the vibrator abstract driver. */ + struct HdfDriverEntry g_vibratorDriverEntry = { + .moduleVersion = 1, // Version of the vibrator module. + .moduleName = "HDF_VIBRATOR", // Vibrator module name. The value must be the same as the value of moduleName in the device_info.hcs file. + .Bind = BindVibratorDriver, // Function for binding a vibrator. + .Init = InitVibratorDriver, // Function for initializing a vibrator. + .Release = ReleaseVibratorDriver, // Function for releasing vibrator resources. + }; + + HDF_INIT(g_vibratorDriverEntry); + ``` + + - Develop the vibrator abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. + + ```c + /* External service published by the vibrator driver. */ + static int32_t DispatchVibrator(struct HdfDeviceIoClient *client, + int32_t cmd, struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t loop; + + for (loop = 0; loop < sizeof(g_vibratorCmdHandle) / sizeof(g_vibratorCmdHandle[0]); ++loop) { + if ((cmd == g_vibratorCmdHandle[loop].cmd) && (g_vibratorCmdHandle[loop].func != NULL)) { + return g_vibratorCmdHandle[loop].func(data, reply); + } + } + + return HDF_SUCCESS; + } + + /* Bind the external service provided by the vibrator driver to the HDF. */ + int32_t BindVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(device, HDF_FAILURE); + + drvData = (struct VibratorDriverData *)OsalMemCalloc(sizeof(*drvData)); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_MALLOC_FAIL); + + drvData->ioService.Dispatch = DispatchVibrator; + drvData->device = device; + device->service = &drvData->ioService; + g_vibratorDrvData = drvData; + + return HDF_SUCCESS; + } + + /* Entry function for vibrator driver initialization. */ + int32_t InitVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + + drvData->mode = VIBRATOR_MODE_BUTT; + drvData->state = VIBRATOR_STATE_IDLE; + ...... + if (CreateVibratorHaptic(device) != HDF_SUCCESS) { + HDF_LOGE("%s: init workQueue fail!", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + + /* Release the resources allocated during vibrator driver initialization. */ + void ReleaseVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + ...... + (void)DestroyVibratorHaptic(); + (void)OsalMutexDestroy(&drvData->mutex); + (void)OsalMemFree(drvData); + g_vibratorDrvData = NULL; + } + ``` + + - During system startup, the HDF configuration management loads the vibrator abstract driver based on the device information HCS and publishes the vibrator driver interfaces. + + ```c + /* Device information HCS. */ + vibrator :: host { + hostName = "vibrator_host"; + device_vibrator :: device { + device0 :: deviceNode { + policy = 2; // Policy for publishing the driver service. + priority = 100; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random. + preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. + permission = 0664; // Permission for the driver to create a device node. + moduleName = "HDF_VIBRATOR"; // Driver name. The value must be the same as that of moduleName in the driver entry structure. + serviceName = "hdf_misc_vibrator"; // Name of the service provided by the driver. The name must be unique. + deviceMatchAttr = "hdf_vibrator_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. + } + } + ``` + +2. Create a vibrator haptic model and parse the haptic HCS configuration. + + - Create a vibrator haptic model. + + ```hcs + /* Create a vibrator haptic model, allocate resources, and parse the haptic HCS configuration. */ + int32_t CreateVibratorHaptic(struct HdfDeviceObject *device) + { + struct VibratorHapticData *hapticData = NULL; + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(device, HDF_FAILURE); + + hapticData = (struct VibratorHapticData *)OsalMemCalloc(sizeof(*hapticData)); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(hapticData, HDF_ERR_MALLOC_FAIL); + g_vibratorHapticData = hapticData; + hapticData->supportHaptic = false; + + if (OsalMutexInit(&hapticData->mutex) != HDF_SUCCESS) { + HDF_LOGE("%s: fail to init mutex", __func__); + goto EXIT; + } + + DListHeadInit(&hapticData->effectSeqHead); + + /* Parse the haptic HCS configuration. */ + if (ParserVibratorHapticConfig(device->property) != HDF_SUCCESS) { + HDF_LOGE("%s: parser haptic config fail!", __func__); + goto EXIT; + } + + return HDF_SUCCESS; + EXIT: + OsalMemFree(hapticData); + return HDF_FAILURE; + } + ``` + + - The vibrator effect model uses the HCS. For details about HCS fields, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md). + + ``` + /* Vibrator data configuration template (vibrator_config.hcs). */ + root { + vibratorConfig { + boardConfig { + match_attr = "hdf_vibrator_driver"; // The value must be the same as that of the match_attr field configured for the vibrator. + vibratorAttr { + /* The value 0 means a rotor vibrator, and 1 means a linear vibrator. */ + deviceType = 1; // Device type. + supportPreset = 1; // Supported preset type. + } + vibratorHapticConfig { + haptic_clock_timer { + effectName = "haptic.clock.timer"; + type = 1; // The value 0 means the built-in mode, and 1 means the time sequence. + seq = [600, 600, 200, 600]; // Time sequence. + } + haptic_default_effect { + effectName = "haptic.default.effect"; + type = 0; + seq = [0, 3, 800, 1]; + } + } + } + } + } + ``` + +3. Develop the interfaces for starting and stopping vibration. A timer will be created and destroyed based on the vibration effect. + + The vibrator hardware service calls **StartOnce** to start one-shot vibration with a given duration and calls **StartEffect** to start vibration with a specified effect. + + ```c + /* Trigger vibration with a given duration. */ + static int32_t StartOnce(struct HdfSBuf *data, struct HdfSBuf *reply) + { + uint32_t duration; + int32_t ret; + struct VibratorEffectCfg config; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + config.cfgMode = VIBRATOR_MODE_ONCE; + config.duration = duration; + config.effect = NULL; + /* Create a timer based on the vibration effect. */ + ret = StartHaptic(&config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: start haptic fail!", __func__); + return ret; + } + + return HDF_SUCCESS; + } + + /* Trigger vibration with a given effect. */ + static int32_t StartEffect(struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t ret; + const char *effect = NULL; + struct VibratorEffectCfg config; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + config.cfgMode = VIBRATOR_MODE_PRESET; + config.duration = 0; + config.effect = effect; + + ret = StartHaptic(&config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: start haptic fail!", __func__); + return ret; + } + + return HDF_SUCCESS; + } + + /* Stop vibration based on the specified vibration mode. */ + static int32_t Stop(struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t ret; + int32_t mode; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + /* Stop vibration and destroy the timer. */ + ret = StopHaptic(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: stop haptic fail!", __func__); + return ret; + } + + (void)OsalMutexLock(&drvData->mutex); + drvData->mode = VIBRATOR_MODE_BUTT; + (void)OsalMutexUnlock(&drvData->mutex); + + return HDF_SUCCESS; + } + ``` + +4. Implement the interfaces for the vibrator chipset driver. + + - Register the vibrator chipset driver interfaces when the vibrator chipset driver is initialized successfully. + + ```c + /* Register the vibrator chipset driver interfaces. */ + int32_t RegisterVibrator(struct VibratorOps *ops) + { + struct VibratorDriverData *drvData = GetVibratorDrvData(); + + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(ops, HDF_FAILURE); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + + (void)OsalMutexLock(&drvData->mutex); + drvData->ops.Start = ops->Start; + drvData->ops.StartEffect = ops->StartEffect; + drvData->ops.Stop = ops->Stop; + (void)OsalMutexUnlock(&drvData->mutex); + + return HDF_SUCCESS; + } + ``` + + - The vibrator driver model provides vibrator chipset driver interfaces. Implement these interfaces as follows: + + ```c + /* Start a linear vibrator to vibrate with a given duration. */ + static int32_t StartLinearVibrator() + { + int32_t ret; + struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + ...... + ret = GpioWrite(drvData->gpioNum, GPIO_VAL_LOW); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_LOW); + return ret; + } + return HDF_SUCCESS; + } + + /* Start a linear vibration to vibrate with a given effect. */ + static int32_t StartEffectLinearVibrator(uint32_t effectType) + { + (void)effectType; + HDF_LOGE("%s: vibrator set build-in effect no support!", __func__); + return HDF_SUCCESS; + } + + /* Stop a linear vibration based on the specified vibration mode. */ + static int32_t StopLinearVibrator() + { + int32_t ret; + struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + ...... + ret = GpioWrite(drvData->gpioNum, GPIO_VAL_HIGH); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_HIGH); + return ret; + } + return HDF_SUCCESS; + } + ``` diff --git a/en/device-dev/driver/figures/sensor_driver_model.png b/en/device-dev/driver/figures/sensor_driver_model.png new file mode 100644 index 0000000000000000000000000000000000000000..ddb564e5a4d4d12f815fd81d526e4992e340a20e Binary files /dev/null and b/en/device-dev/driver/figures/sensor_driver_model.png differ diff --git a/en/device-dev/driver/figures/sensor_working.png b/en/device-dev/driver/figures/sensor_working.png new file mode 100644 index 0000000000000000000000000000000000000000..b2a8468d152ba9ddd0c36764c329c59c6725cced Binary files /dev/null and b/en/device-dev/driver/figures/sensor_working.png differ diff --git a/en/device-dev/driver/figures/vibrator_driver_model.png b/en/device-dev/driver/figures/vibrator_driver_model.png new file mode 100644 index 0000000000000000000000000000000000000000..9d377d21c044927727cab59f76fc0f0486423f1f Binary files /dev/null and b/en/device-dev/driver/figures/vibrator_driver_model.png differ diff --git a/en/device-dev/driver/figures/vibrator_working.png b/en/device-dev/driver/figures/vibrator_working.png new file mode 100644 index 0000000000000000000000000000000000000000..edf0dce07514add0db9394a200ebb2f0bc1f572e Binary files /dev/null and b/en/device-dev/driver/figures/vibrator_working.png differ diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index 0ad09b4a3488a6512c86a6175682da5c63868465..0f37c6654ed3d5728e3dd6d7c3e66d0fc283151d 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -74,6 +74,7 @@ - [Startup](subsys-boot-overview.md) - [init Module](subsys-boot-init.md) - [appspawn Module](subsys-boot-appspawn.md) + - [appspawn Module for the Standard System](subsys-boot-appspawn-standard.md) - [bootstrap Module](subsys-boot-bootstrap.md) - [syspara Module](subsys-boot-syspara.md) - [FAQs](subsys-boot-faqs.md) diff --git a/en/device-dev/subsystems/subsys-boot-appspawn-standard.md b/en/device-dev/subsystems/subsys-boot-appspawn-standard.md new file mode 100644 index 0000000000000000000000000000000000000000..06019edbb3695df60f5a9d3c0aa8022d6f6e569e --- /dev/null +++ b/en/device-dev/subsystems/subsys-boot-appspawn-standard.md @@ -0,0 +1,158 @@ +# appspawn Module for the Standard System + +## Overview + +After being started by the init process, the appspawn process waits for inter-process communication (IPC) messages. Upon receiving a message, the appspawn process starts an application service based on the message content, and grants the corresponding permission to the application service. + +### Introduction + +- Security control +
Support for setting of SELinux tags for applications + +- Application process control + + - Support for setting of AccessToken for applications + - Support for simultaneous stopping of all spawn application processes (after stopping of the appspawn process and before a restart) + +- Cold start +
Support for cold start of applications by using the **aa** command + + ``` + param set appspawn.cold.boot true // Enable cold start. + aa start -d 12345 -a $name -b $package -C + Example: + aa start -d 12345 -a ohos.acts.startup.sysparam.function.MainAbility -b ohos.acts.startup.sysparam.function -C + +### Basic Concepts + +**appspawn** is a registered service name. The appspawn process receives requests from the client by listening to messages over the local socket. The message type is an **AppProperty** structure. It is defined in **base/startup/appspawn_standard/interfaces/innerkits/include/sclient_socket.h**. + +**Table 1** Field description + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

+

Description

+

processName

+

Name of the service process to be started. The value contains a maximum of 256 bytes.

+

bundleName

+

Bundle name of the application to be started. The value contains a maximum of 256 bytes.

+

soPath

+

Path of the dynamic library specified by the application. The value contains a maximum of 256 bytes.

+

uid

+

UID of the application process to be started. The value must be a positive number.

+

gid

+

GID of the application process to be started. The value must be a positive number.

+

gidTable

+

Information about the application process group to be started. Its length is specified by **gidCount**. A maximum of 64 process groups are supported. The value must be a positive number.

+

gidCount

+

Number of application process groups to be started.

+

accessTokenId

+

Token ID for application process permission control.

+

apl

+

APL for application process permission control. The value contains a maximum of 32 bytes.

+
+ +## Development Guidelines + + The API definitions are provided in **base/startup/appspawn_standard/interfaces/innerkits/include/client_socket.h**. Table 2 is a list of available APIs. + +### Available APIs + +**Table 2** Available APIs + + + + + + + + + + + + + + + + + + + + +

Field

+

Description

+

CreateClient

+

Creates a client.

+

CloseClient

+

Closes a client.

+

ConnectSocket

+

Sends a connection request to the appspawn service.

+

WriteSocketMessage

+

Sends a message to the appspawn service.

+

ReadSocketMessage

+

Receives a message from the appspawn service.

+
+ +### Development Example + +
The following is an example of using related APIs: +``` + std::shared_ptr clientSocket = std::make_unique("AppSpawn"); + if (clientSocket == nullptr) { + return -1; + } + if (clientSocket->CreateClient() != ERR_OK) { + return -1; + } + if (clientSocket->ConnectSocket() != ERR_OK) { + return -1;; + } + // Construct AppProperty based on the specified property. + clientSocket->WriteSocketMessage((void *)&property, sizeof(AppSpawn::AppProperty)); + // Read the result. + int pid; + clientSocket->ReadSocketMessage((void *)&pid, sizeof(pid)); + // Normally, the process ID of the application is returned. If the PID is less than or equal to 0, an error has occurred. +``` + +## FAQ + +### Cold Start Failure + +   **Symptom** +
    Cold start failed because of a command execution failure. + +   **Solution** +
    1. Check whether cold start is enabled. +
    2. Check whether the cold start command is correct. diff --git a/en/device-dev/subsystems/subsys-boot-init.md b/en/device-dev/subsystems/subsys-boot-init.md index 1be8617beeba51061bf79045576dd3e50f3f7139..4fff3dafd166be597885752587fee0885545447b 100644 --- a/en/device-dev/subsystems/subsys-boot-init.md +++ b/en/device-dev/subsystems/subsys-boot-init.md @@ -1,58 +1,135 @@ # init Module -- [Configuration File](#section56901555917) -- [Development Guidelines](#section15371931131117) -- [Development Example](#section173413113565) +## Introduction -The init module starts key service processes during system startup. If you would like to add a system service that automatically starts upon system startup, you can add the service to the **init.cfg** file. + The init module starts key service processes during system startup. If you would like to add a system service that automatically starts upon system startup, you can add a configuration file named in the **xxx.cfg** format. The system automatically analyzes the **.cfg** file and starts the corresponding service. -## Configuration File of the init Module +- Configuration file of the init module -The configuration file **init.cfg** of the init module contains service names, executable file paths, permissions, and other information of all key system services that need to be started by the init process. The file is stored in the code repository **vendor/huawei/camera/init\_configs/**, and can be found in **/etc/** after burning is complete. The file is in JSON format, and its size cannot exceed 100 KB. + The configuration file of the init module, that is, **init.cfg**, contains service names, executable file paths, permissions, and other information of all key system services that need to be started by the init process. The file can be found in **/etc/** after burning is complete. The file is in JSON format, and its size cannot exceed 100 KB. -After the init process starts, it reads the **/etc/init.cfg** file, parses the content in JSON format, and loads system services in sequence based on the parsing result. + After the init process starts, it reads the **/etc/init.cfg** file, parses the content in JSON format, and loads system services in sequence based on the parsing result. -## Development Guidelines + If you need to add a key service to a module, you can also add the **.cfg** file of the module. During compilation, copy the file to the **/system/etc/init** directory. The init process will parse the **.cfg** file and starts the corresponding service. -1. Configure the **jobs** array. +- init service startup control (for standard system or higher) - The init module completes the system startup in three phases: + The init process classifies services into three types based on service configurations and starts the services in different phases. - - **pre-init**: operations required before system services are started, for example, mounting a file system, creating a folder, and modifying permissions. - - **init**: operations required for starting system services. - - **post-init**: operations required after system services are started. + - **boot**: services that need to be preferentially started in the system. This type of services are started after the init phase is complete. + - **normal**: common services in the system. These services are started after the init command is executed successfully. This is the default service type. + - **condition**: services with special requirements. You can run the **start xxx** command to start such a service. Generally, this type of services are started in a condition job or in a certain phase of the init process. - Each of the preceding phases is represented by a job, which corresponds to a command set. The init module initializes the system by executing the commands in each job in sequence. The **pre-init** job is executed first, then the **init** job, and finally the **post-init** job. + If dependencies exist between services or between services and commands, you need to use **condition** to describe services. For example: + ``` + "services" : [{ + "name" : "service1", + "path" : ["/bin/process1", "param1", "param2"], + "uid" : 1, + "gid" : 1, + "once" : 0, + "importance" : 1, + "caps" : [0, 1, 2, 5], + "start-mode" : "condition", + "cpucore" : [0], + "critical" : [0, 5, 10], + "apl" : "normal", + "d-caps" : ["OHOS_DMS"] + "jobs" : { + "on-boot" : "boot", + "on-start" : "services:service1_start", + "on-stop" : "services:service1_stop", + "on-restart" : "services:service1_restart" + } + }, + + ``` +- init parallel service control (for standard system or higher) + + The init module provides the parallel service processing function, which allows services to execute jobs in different phases. + + - **on-start**: a job executed after the service process is forked. The on-start jobs of different services can be executed in parallel. (The on-start job is executed in the subprocess of the service and affects only the subprocess.) + - **on-stop**: a job executed when the service is stopped. + - **on-restart**: a job executed when the service is restarted. + +- init on-demand startup (for standard system or higher) + + Services managed by the init process can be started on demand. Such services are not automatically started during system startup. Instead, they are started by the init process only when a certain event occurs. Typical events that trigger service startup are as follows: Messages are sent over the socket listened by the init process. The samgr process receives a request from the client and needs to start the SA service. + + The **ondemand** attribute indicates whether a service is started on demand. If this attribute is set to **true** for a service, the service does not need to be started by running the **start** command. Instead, it is started only when the corresponding event occurs. + + - SA process on-demand startup + 1. When an application requests an SA handle, the samgr process checks whether the process to which the SA belongs can be dynamically started. + 2. If the SA process needs to be started, the samgr process blocks the request. After the init process starts and registers the SA process, the samgr process returns the SA handle. + + - Socket process on-demand startup + 1. The init process creates a socket for socket processes in the pre-fork phase, and listens to network events on this socket. + 2. When messages are detected on the socket, the init process starts the socket process for message processing. The init process then stops listening to network data over the socket and waits until the socket process completes message processing. + 3. If no more messages need to be processed, the socket process can automatically exit. After that, the init process reclaims the subprocess and listens to network data over the socket again. + + - Hot-swap service process on-demand startup +
  The hot-swap service process can be started to process hot swap events based on system parameter changes. + +- Enhanced init process startup and recycling + + The CPU core binding, priority, MAC address, and AccessToken information of the service process can be configured in the configuration file during process startup. + + - Support of CPU core binding for service processes (through modification of the **.cfg** file) + - Support of priority setting for service processes (through modification of the **.cfg** file) + - Support of AccessToken setting for service processes and distributed capability setting for system service processes (through modification of the **.cfg** file) + - Support of the suppression mechanism for service processes (through modification of the **.cfg** file) + +- init fd proxy (for standard system or higher) + + fd proxy is an extended mechanism for on-demand startup. It can ensure that the fd state handle is not lost before the service process exits. Specifically, a service process sends the fd to the init process before it exits, and then reclaims the fd from the init process when it is started again. + + This mechanism is implemented using the API provided by the init process. Before a service process exits, it can call the related API to send the fd to the init process over the socket that supports IPC communication. After the service process is restarted, the init process returns the corresponding fd handle to it in the same way. + +- init job + + A job provided by the init process. It is actually a set of commands. 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. - ``` - "jobs" : [{ - "name" : "pre-init", - "cmds" : [ - "mkdir /testdir", - "chmod 0700 /testdir", - "chown 99 99 /testdir", - "mkdir /testdir2", - "mount vfat /dev/mmcblk0p0 /testdir2 noexec nosuid" // mount command (format: mount file system type source target flags data) - ] + - Common job: A job executed in a fixed phase during init process startup, for example, pre-init, init, or post-init. + + - Custom job: A job is triggered based on certain rules. + - job: A user-defined job, which can be executed using the **trigger** command. + - Control job (for standard system or higher): A job triggered based on specified conditions. You can set trigger conditions in such a job. When the corresponding attribute values meet the trigger conditions, the job will be triggered. && and || operations are supported for trigger conditions, and these operations can be used in flexible combinations as needed. + +## Development Guidelines + + 1. Configure the **jobs** array. + + The init module completes the system startup in three phases: + + - **pre-init**: operations required before system services are started, for example, mounting a file system, creating a folder, and modifying permissions. + - **init**: operations required for starting system services. + - **post-init**: operations required after system services are started. + + ``` + "jobs" : [{ + "name" : "pre-init", + "cmds" : [ + "mkdir /testdir", + "chmod 0700 /testdir", + "chown 99 99 /testdir", + "mount vfat /dev/mmcblk0p0 /testdir2 noexec nosuid" // mount command (format: mount file system type source target flags data) + ] }, { - "name" : "init", + "name" : "init", "cmds" : [ - "start service1", - "start service2" - ] - }, { - "name" : "post-init", - "cmds" : [] - } - ], - ``` - - **Table 1** Job description + "start service1", + ] + }, { + "name" : "post-init", + "cmds" : [] + } + ] + ``` - -

Job

+**Table 1** Job description + - @@ -68,20 +145,16 @@ After the init process starts, it reads the **/etc/init.cfg** file, parses the c -

Job

Description

+

Description

post-init

Job that is finally executed. Operations (for example, mounting the device after the driver initialization) required after the process startup are executed in this job.

+

Job that is finally executed. Operations (for example, mounting the device after the driver initialization) required after the process startup are executed in this job. A single job can hold a maximum of 30 commands (Only start, mkdir, chmod, chown, mount, and loadcfg are supported currently). The command name and parameters (128 bytes or less) must be separated by only one space.

- A single job can hold a maximum of 30 commands (only **start**, **mkdir**, **chmod**, **chown**, **mount**, and **loadcfg** are supported currently). The command name and parameters (128 bytes or less) must be separated by only one space. - - **Table 2** Commands supported by a job - - -

Command

+**Table 2** Commands supported by a job + - @@ -136,40 +209,52 @@ After the init process starts, it reads the **/etc/init.cfg** file, parses the c -

Command

Format and Example

+

Format and Example

Description

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.

+

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.

-2. Configure the services array, which holds all system services (a maximum of 100) that need to be started by the init process. - - ``` - "services" : [{ - "name" : "service1", - "path" : ["/bin/process1", "param1", "param2"], - "uid" : 1, - "gid" : 1, - "once" : 0, - "importance" : 1, - "caps" : [0, 1, 2, 5] - }, { - "name" : "service2", - "path" : "/bin/process2", - "uid" : 2, - "gid" : 2, - "once" : 1, - "importance" : 0, - "caps" : [ ] - } - ] - ``` + 2. Configure the services array, which holds all system services (a maximum of 100) that need to be started by the init process. - **Table 3** Fields in the services array +``` + "services" : [{ + "name" : "service1", + "path" : ["/bin/process1", "param1", "param2"], + "uid" : 1, + "gid" : 1, + "once" : 0, + "importance" : 1, + "caps" : [0, 1, 2, 5], + "start-mode" : "condition", + "cpucore" : [0], + "critical" : [0, 5, 10], + "apl" : "normal", + "d-caps" : ["OHOS_DMS"] + "jobs" : { + "on-boot" : "boot", + "on-start" : "services:service1_start", + "on-stop" : "services:service1_stop", + "on-restart" : "services:service1_restart" + } + }, { + "name" : "service2", + "path" : "/bin/process2", + "uid" : 2, + "gid" : 2, + "once" : 1, + "importance" : 0, + "caps" : [ ], + "cpucore" : 0, + "critical" : [ ], + "apl" : "normal", + "d-caps" : [ ] + }] +``` + +**Table 3** Service field description - -

Field

+ @@ -205,9 +290,7 @@ After the init process starts, it reads the **/etc/init.cfg** file, parses the c - + + + + + + + + + + + + + + + + + + + + + +

Field

Description

importance

Whether the current service process is a key system process.

-

0: The current service process is not a key system process. If it exits, the init process does not reset or restart the system.

-

1: The current service process is a key system process. If it exits, the init process resets and restarts the system.

+

Standard system:
Priority of a service process. The value ranges from -20 to 19.
Small system:
0: non-critical process
1: critical process

caps

@@ -215,13 +298,57 @@ After the init process starts, it reads the **/etc/init.cfg** file, parses the c

Capabilities required by the current service. They are evaluated based on the capabilities supported by the security subsystem and configured in accordance with the principle of least permission. Currently, a maximum of 100 values can be configured.

critical

+

Whether to enable system restarting when a critical service fails to be restarted for a specified number of times. If this field is enabled, the critical service will be started in M seconds. If the restarting fails for N times, the system will be restarted. The default value of N is 4 and that of M is 20. (Only for standard system or higher. Configuration: [0, 2, 10], in int array.)

+

0: enable

+

1: disable

+

cpucore

+

Number of CPU cores bound to the service. The value is an int array.

+

d-caps

+

Distributed capabilities (Only for standard system or higher)

+

apl

+

Ability privilege level: system_core, normal, or system_basic. The default value is system_core. (Only for the standard system or higher).

+

start-mode

+

Service startup mode. For details, see init Service Startup Control. (Only for standard system or higher)

+

jobs

+

Jobs that can be executed by the current service in different phases. For details, see init Service Parallel Service Control. (Only for standard system or higher)

+
+ **Table 4** APIs + + | API | Function|Description | + | :---------- | :---------- |:--------| + | int *ServiceGetFd(const char *serviceName, size_t *outfdCount) | Obtains the fd from the init process.| Return value: Returns the pointer to the fd array if the operation is successful; returns **NULL** otherwise. (Note: Manual release is required.)
Input arguments:
**serviceName**: service name.
**outfdCount**: length of the returned fd array.| + | int ServiceSaveFd(const char *serviceName, int *fds, int fdCount) | Requests the init process for fd proxy.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.
Input arguments:
**serviceName**: service name.
**fds**: pointer to the fd array for fd proxy.
**fdCount**: length of the fd array + | int ServiceControlWithExtra(const char *serviceName, int action, const char *extArgv[], int extArgc) | Configures service parameters.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.
Input arguments:
**serviceName**: service name.
**action**: service action, which can be **start**, **stop**, or **restart**.
**extArgv**: parameter array.
**extArgc**: number of parameters. + | int ServiceControl(const char *serviceName, int action) | Controls the service behavior.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.
Input arguments:
**serviceName**: service name.
**action**: service action, which can be **start**, **stop**, or **restart**. -## Development Example +## Development Example -The following uses the MySystemApp service as an example to illustrate how to use the init process to start a system service. + The following uses the MySystemApp service as an example to illustrate how to use the init process to start a system service. ``` { @@ -250,6 +377,14 @@ The following uses the MySystemApp service as an example to illustrate how to us "once" : 0, // Not a one-off process of the MySystemApp service. If MySystemApp exits, the init process needs to restart it. "importance" : 0, // Not a key system process of the MySystemApp service. If MySystemApp exits, the init process does not need to restart the development board. "caps" : [] // Do not perform capability-related operations because capabilities are not required by the MySystemApp service. + "start-mode" : "condition", + "critical": [1, 2, 10], // Configure the critical field for MySystemApp system services. You need to pass three parameters, wherein, 1 means to enable system restarting, 2 means the number of times the critical service is restarted, and 10 means the time within which the critical service is restarted. + "jobs" : { + "on-boot" : "boot", + "on-start" : "services:MySystemApp_start", + "on-stop" : "services:MySystemApp_stop", + "on-restart" : "services:MySystemApp_restart" + } } ] } @@ -260,3 +395,41 @@ After the configuration is complete, compile the package to burn the board. 1. Run the **task -a** command for liteos-a or **ps** for Linux to check whether the MySystemApp service process is started. 2. Run the **kill** command to kill the MySystemApp process, and then verify that the process will be restarted. 3. Run the **kill** command to kill the MySystemApp process, and then verify that the development board will not be restarted. + +## FAQ + +### Service Not Exist + +   **Symptom**
+    "Failed get servName" is recorded in the kernel log. + +   **Cause Analysis**
+     The kernel log is printed by the init process. After a code review on the init process, it is found that the service does not exist. + +   **Solution**
+     1. Check whether the service is correctly configured in the **.cfg** file.
+     2. Check whether the **.cfg** file of the service is loaded normally.
+     3. Check whether the format of the **.cfg** file is correct. + +### Requesting FD Proxy for Other Services Failed + +  **Symptom** + +     "Service \' xxx \'(pid = xxx) is not valid or request with unexpected process(pid = xxx)" is recorded in the kernel log. + +   **Cause Analysis**
+     The kernel log is printed by the init process. After a code review on the init process, it is found that fd proxy is requested for other services. + +   **Solution**
+     Request fd proxy for the current service, but not other services. + +### No ondemand Configuration is not configured for the service. + +   **Symptom**
+     "service: %s had started already" is recorded in the kernel log. + +   **Cause Analysis**
+     The kernel log is printed by the init process. After a code review on the init process, it is found that **ondemand** is not configured for the service. + +   **Solution**
+     Correct the service configuration in the **.cfg** file as follows: "ondemand" : true diff --git a/en/readme/ark-runtime.md b/en/readme/ark-runtime.md index 702e3e169a519b33bd1bfce55bef68d77b5829a9..9f0c80feec48f186591c107ec0a7e4bdb79f4358 100644 --- a/en/readme/ark-runtime.md +++ b/en/readme/ark-runtime.md @@ -2,7 +2,7 @@ ## Introduction -ARK is a unified programming platform developed by Huawei. Its key components include a compiler, toolchain, and runtime. ARK supports compilation and execution of high-level programming languages on the multiple hardware platform and accelerates the execution of the OpenHarmony operating system and its applications and services on mobile phones, PCs, tablets, TVs, automobiles, and smart wearables. The ARK-JS open sourced this time provides the capability of compiling and running the JavaScript \(JS\) language on the standard system of OpenHarmony. +ARK is a unified programming platform developed. Its key components include a compiler, toolchain, and runtime. ARK supports compilation and execution of high-level programming languages on the multiple hardware platform and accelerates the execution of the OpenHarmony operating system and its applications and services on mobile phones, PCs, tablets, TVs, automobiles, and smart wearables. The ARK-JS open sourced this time provides the capability of compiling and running the JavaScript \(JS\) language on the standard system of OpenHarmony. The ARK-JS consists of two parts: JS compiler toolchain and JS runtime. The JS compiler toolchain compiles JS source code into ARK bytecodes. The JS runtime executes the generated ARK bytecodes. Unless otherwise specified, bytecodes refer to ARK bytecodes in this document. diff --git a/en/release-notes/OpenHarmony-v3.1-beta.md b/en/release-notes/OpenHarmony-v3.1-beta.md index 1d120d7ce6282bcbddeb90f3a6f05d21afbc3a18..e951f515c36d7d78afd9da247186754a7c816bf5 100644 --- a/en/release-notes/OpenHarmony-v3.1-beta.md +++ b/en/release-notes/OpenHarmony-v3.1-beta.md @@ -29,6 +29,25 @@ OpenHarmony 3.1 Beta provides the following enhancements over OpenHarmony 3.0 LT ## 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) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure basic 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 access permission to this directory, download the tool to any other accessible directory and configure the directory to the environment variable. + chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` ### Acquiring Source Code Using the repo Tool @@ -80,29 +99,29 @@ This version has the following updates to OpenHarmony 3.0 LTS. | Subsystem| Standard System| Mini and Small Systems| | -------- | -------- | -------- | -| Bundle management framework| - I4MBSE: Provides the home screen bundle management client.
- I4MBSF: Supports cache clearing.
- I4MBSG: Supports installation package information query.
- I4MBSD: Supports multi-HAP installation.
- I4MBSH: Supports signature verification during multi-HAP installation.
- I4MBSC: Supports the **srcPath** field for modules and abilities.| NA | -| Distributed Scheduler subsystem| -I4MBRW: Samgr supports intra-process system ability list control.
-I4MBRV: Samgr supports maintenance of the system service status list.
-I4MBRZ: Samgr supports initialization of the full service list.
-I4MBRY: Samgr supports maintenance of the system process status list.
-I4MBRX: Samgr supports loading a specific system service.| NA | -| DeviceProfile subsystem| -I4NY23: Insertion, deletion, and query of local device profiles.
-I4NY1X: Query of remote device profiles.
-I4NY1T: Subscription to remote profile changes.
-I4NY1W: Cross-device profile synchronization.| NA | -| Account subsystem| -I4MBQW: Application account addition and deletion.
-I4MBQV: Restrictions on the basic information about application accounts.
-I4MBQU: Application account subscription and unsubscription.
-I4MBQT: Application account function setting and content modification.
-I4MBQS: Application account information query.
-I4IT3U: Basic information management for application accounts.| NA | -| Pan-sensor subsystem| -I3NJ96: Acceleration sensor data reporting.
-I3NJ8H: Gyroscope sensor data reporting.
-I3NJ7J: Ambient light sensor data reporting.
-I3NJ76: Magnetic field sensor data reporting.
-I4MBRP: Magnetic declination and dip.
-I4MBRQ: Horizontal intensity and total intensity of the magnetic field.| NA | -| USB subsystem| I410OZ:
- Querying the list of connected USB devices.
- Obtaining the temporary permission to access USB devices.
- Setting USB device configurations and interfaces.
- Data transfer using USB devices.| NA | -| Multi-language Runtime subsystem| - I4MBUK: The default runtime of JS/TS is changed from quickjs to ARK.
- I4MBUJ: The memory reclaim capability of ARK runtime is enhanced. The concurrent marking and concurrent compression algorithms are supported. Some regions can be selected for compression GC, reducing the GC pause time by 30%.| NA | -| Globalization subsystem| - Added globalization features: singular and plural rules, string sorting, phone number processing, calendar and local calendar, weights and measures and formatting, locale representations and attributes, time segment formatting, alphabet retrieval, Unicode character attributes, wrapping and line feed.
- Supports system resources and rawfile resources.| NA | -| DSoftBus subsystem| -I4FZ29: DSoftBus provides the Ext API for transmission.
-I4FZ25: DSoftBus supports network switching.| -I4FZ29: DSoftBus provides the Ext API for transmission.
-I4FZ25: DSoftBus supports network switching.| -| Startup subsystem| NA | -I3XGJH: init basic environment building.
-I3XGKV: System parameter management.
-I3XGLN: init script management.
-I3XGMQ: Basic permission management.
-I3XGN8: Boot image building and loading.
-I3XGKV: uevent management.
-I3XGNM: Burning mode.| -| Media subsystem| NA | -I4BX5Z: HiStreamer supports audio playback and control.
-I4BX8A: HiStreamer supports playback of MP3 and WAV audio files.
-I4BX9E: HiStreamer playback engine framework requirements are met.
-I4DK89: HiStreamer plugin framework requirements are met.
-I4DK8D: HiStreamer performance and DFX requirements are met.| -| Graphics subsystem| New design of the OpenHarmony graphics stack:
Added the background rendering feature to the UI framework.
Supports the access to the background rendering module of RenderService from ArkUI components.| NA | -| Kernel subsystem| Kernel (Linux 5.10):
-I4LUG4: Supports Contiguous Memory Area (CMA) reuse. (Currently, only Hi3516D V300 is supported.)
-I4LX4G: Supports anonymous Virtual Memory Area (VMA) naming. (Currently, only Hi3516D V300 is supported.)| -I3ND6Y: Optimized OS kernel and driver startup performance.| +| Bundle management framework| - I4MBSE: Provides the home screen bundle management client.
- I4MBSF: Supports cache clearing.
- I4MBSG: Supports installation package information query.
- I4MBSD: Supports multi-HAP installation.
- I4MBSH: Supports signature verification during multi-HAP installation.
- I4MBSC: Supports the **srcPath** field for modules and abilities.| NA | +| Distributed Scheduler subsystem| -I4MBRW: Samgr supports intra-process system ability list control.
-I4MBRV: Samgr supports maintenance of the system service status list.
-I4MBRZ: Samgr supports initialization of the full service list.
-I4MBRY: Samgr supports maintenance of the system process status list.
-I4MBRX: Samgr supports loading a specific system service.| NA | +| DeviceProfile subsystem| -I4NY23: Insertion, deletion, and query of local device profiles.
-I4NY1X: Query of remote device profiles.
-I4NY1T: Subscription to remote profile changes.
-I4NY1W: Cross-device profile synchronization.| NA | +| Account subsystem| -I4MBQW: Application account addition and deletion.
-I4MBQV: Restrictions on the basic information about application accounts.
-I4MBQU: Application account subscription and unsubscription.
-I4MBQT: Application account function setting and content modification.
-I4MBQS: Application account information query.
-I4IT3U: Basic information management for application accounts.| NA | +| Pan-sensor subsystem| -I3NJ96: Acceleration sensor data reporting.
-I3NJ8H: Gyroscope sensor data reporting.
-I3NJ7J: Ambient light sensor data reporting.
-I3NJ76: Magnetic field sensor data reporting.
-I4MBRP: Magnetic declination and dip.
-I4MBRQ: Horizontal intensity and total intensity of the magnetic field.| NA | +| USB subsystem| I410OZ:
- Querying the list of connected USB devices.
- Obtaining the temporary permission to access USB devices.
- Setting USB device configurations and interfaces.
- Data transfer using USB devices.| NA | +| Multi-language Runtime subsystem| - I4MBUK: The default runtime of JS/TS is changed from quickjs to ARK.
- I4MBUJ: The memory reclaim capability of ARK runtime is enhanced. The concurrent marking and concurrent compression algorithms are supported. Some regions can be selected for compression GC, reducing the GC pause time by 30%.| NA | +| Globalization subsystem| - Added globalization features: singular and plural rules, string sorting, phone number processing, calendar and local calendar, weights and measures and formatting, locale representations and attributes, time segment formatting, alphabet retrieval, Unicode character attributes, wrapping and line feed.
- Supports system resources and rawfile resources.| NA | +| DSoftBus subsystem| -I4FZ29: DSoftBus provides the Ext API for transmission.
-I4FZ25: DSoftBus supports network switching.| -I4FZ29: DSoftBus provides the Ext API for transmission.
-I4FZ25: DSoftBus supports network switching.| +| Startup subsystem| NA | -I3XGJH: init basic environment building.
-I3XGKV: System parameter management.
-I3XGLN: init script management.
-I3XGMQ: Basic permission management.
-I3XGN8: Boot image building and loading.
-I3XGKV: uevent management.
-I3XGNM: Burning mode.| +| Media subsystem| NA | -I4BX5Z: HiStreamer supports audio playback and control.
-I4BX8A: HiStreamer supports playback of MP3 and WAV audio files.
-I4BX9E: HiStreamer playback engine framework requirements are met.
-I4DK89: HiStreamer plugin framework requirements are met.
-I4DK8D: HiStreamer performance and DFX requirements are met.| +| Graphics subsystem| New design of the OpenHarmony graphics stack:
Added the background rendering feature to the UI framework.
Supports the access to the background rendering module of RenderService from ArkUI components.| NA | +| Kernel subsystem| Kernel (Linux 5.10):
-I4LUG4: Supports Contiguous Memory Area (CMA) reuse. (Currently, only Hi3516D V300 is supported.)
-I4LX4G: Supports anonymous Virtual Memory Area (VMA) naming. (Currently, only Hi3516D V300 is supported.)| -I3ND6Y: Optimized OS kernel and driver startup performance.| | Startup subsystem| NA | -I3NTCT: The Linux init process supports hot swap.| | Distributed Data Management subsystem| NA | -I4H3JJ: Provides distributed objects for small-system devices.| -| Telephony subsystem| NA | -I4JQ2N: Provides HTTP JS APIs.
-I4JQ3G: Supports HTTP 2.0.| -| Misc Services subsystem| I4MBQE:
Enables applications to read the system time.
Enables applications to read the system time zone.
Provides time change notifications.
Provides time zone change notifications.
Provides minute change notifications.| NA | -| Compilation and Building subsystem| I4K7E3: Provides a unified compilation command as the compilation entry.
-I4KCNB: Supports the unified gn template.| -I4MBQN: Supports a unified compilation entry and uses **build.sh** to compile mini- and small-system devices.
-I4MBQP: Supports a unified compilation process.
-I4MBQR: Supports unified product configuration.| +| Telephony subsystem| NA | -I4JQ2N: Provides HTTP JS APIs.
-I4JQ3G: Supports HTTP 2.0.| +| Misc Services subsystem| I4MBQE:
Enables applications to read the system time.
Enables applications to read the system time zone.
Provides time change notifications.
Provides time zone change notifications.
Provides minute change notifications.| NA | +| Compilation and Building subsystem| I4K7E3: Provides a unified compilation command as the compilation entry.
-I4KCNB: Supports the unified gn template.| -I4MBQN: Supports a unified compilation entry and uses **build.sh** to compile mini- and small-system devices.
-I4MBQP: Supports a unified compilation process.
-I4MBQR: Supports unified product configuration.| | File Storage subsystem| -I4MBS2: Provides StatFS JS interfaces for obtaining the total space and free space of a device.| NA | -| Driver subsystem| -I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted.
-I4L3LF: The sensor driver model capability is enhanced to support cross-process service obtaining and invoking of sensor HDIs.
-I4MBTS: Provides more capabilities for HDF input devices and supports data reporting of joystick devices.
-I4MBTR: The default reference implementation of the Display HDI interface for the standard system is provided based on the DRM display architecture, which helps vendors to adapt the HDI.
-I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface.
-I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels.
-I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management.| -I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted.
Provides more capabilities for HDF input devices (running on Linux) and supports data reporting of joystick devices.
-I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface.
-I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels.
-I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management.| -| ArkUI| - I4MBUY: Added **target** to the event to obtain the size.
- I4MBUZ: The **\** component supports cache setting.
- I4MBV1: The **\** component supports synchronous and asynchronous rendering setting.
- I4MBV3: Added the component polymorphic style setting to the style setting feature.
- I4MBV5: Added the pop-up text for menu content extension to the **\** component.
- I4MBV6: Added the custom container components to the component customization feature.
- I4MBV7: Added scroll bar style customization.
- I4MBV8: Added switching forbidden for the **\** component.
- I4MBV9: Added tab bar content customization for the **\** component.
- I4MBVA: Added title bar setting for the **\** component.
- I4MBVB: Added toolbar display/hide control for the **\** component.
- I4MBVC: Added content customization for the **\** component.
- I4MBVD: Added the SysCap declaration compilation feature.
- I4MBVE: Added the JSSDK compilation feature.
- I4MBVF: Added the **Config.json** compilation feature.
- I4MBVG: Added the breakpoint debugging feature for single-instance debugging.
- I4MBVH: Added the attach debugging feature for single-instance debugging.
- I4MBVI: Added the declarative paradigm compilation feature to support compilation and verification.
- I4MBVJ: Added the JS module shared compilation feature.
- I4MBVK: Added the HAR reference and compilation feature.
- I4MBVL: Added the HPM reference and compilation feature.
- I4MBVN: Added the vertical display of the slider bar.
- I4MBVO: Added the content customization feature for the **\** component.
- I4MBVP: Added the drawing capability for the **\** component.
- I4MBVQ: Enhanced the capabilities of the **\** component.
- I4MBVR: Added the touch target setting.
- I4MBVS: Added the support for Lottie animation.
- I4MBVT: Added the feature for obtaining the component size.
- I4MBVU: Added content customization to the **\** component.
- I4MBVV: Added the support for the **\** gesture.
- I4MBVW: Added the inspector capability for UI preview.
- I4MBVX: Added the non-route file preview feature.
- I4MBVY: Added the NAPI preview feature.
- I4MBVZ: Added the declarative paradigm preview feature with the basic preview supported.
- I4MBW2: Added the declarative paradigm hot loading feature for modification to the existing nodes.
- I4MBW3: Added the declarative paradigm hot loading feature for node addition.
- I4MBW4: Added the declarative paradigm hot loading feature for node deletion.
- I4MBW5: Added the component preview feature and the page component preview.
Added the universal attribute **touchable** to specify whether a component is touchable.
Added the basic component **\**.
Added the basic component **\**.
Added the basic component **\